Jquery如果复选框被选中,启动开关

Jquery if checkbox is checked Bootstrap switch

本文关键字:启动 开关 如果 复选框 Jquery      更新时间:2023-09-26

我使用Bootstrap开关插件使我的复选框看起来像开关按钮。我需要检查复选框是否在jQuery中被选中。我在谷歌上搜索了很多,我尝试了一些建议和代码片段,但没有成功。

我认为我找到的最干净的代码是

$('#checkbox').attr('checked');

,但它仍然不能在我的网站工作。我已经在头部声明了jQuery。我尝试在非引导开关复选框上使用这个片段,但仍然没有成功。

JS:

 <script>
    $(function(){
      $(".odeslat").click(function(){
           $('#pozadavky').slideUp(100);
           $('#datumpick').slideDown(300);
       var typpaliva = 'nic';
       var malpg = 'nic';¨
       /***Important condition***/
       if ($('#uho').attr('checked')) {
            $.cookie("typpaliva", "Diesel");
       }
       else {
            $.cookie("typpaliva", "Benzin");
       }

 /**********************************************/

    $.ajax({
   url: 'http://podivej.se/script_cas.php',
   data: {druh: '30'},
   type: "POST",
   success: function(data){
            alert($.cookie('typpaliva')); 
            alert($.cookie('malpg'));   
   }
   });
  });
});
</script> 

<input type="checkbox" name="testcheckbox" id="uho"/>

使用说明:

if ($('#uho').is(':checked')) {

代替

if ($('#uho').attr('checked')) {

Demo

.prop() 代替.attr()

  • .prop返回- 'true'或'false'。使用这个
  • .is(':checked')返回- 'true'或'false' - :checked是一个伪选择器。
  • .attr返回- '已检查'或'属性未定义'。

$('#uho').prop('checked')
if($('#uho').prop('checked')){
    $.cookie("typpaliva", "Diesel");
}
else {
    $.cookie("typpaliva", "Benzin");
}

根据接受答案中的评论,我是如何解决bootstrap中的条款和条件复选框的问题的:

HTML

<div class="checkbox">
   <label>
      <input id="agreeTAC" type="checkbox" value="">
      I have read and agree to the TERMS AND CONDITIONS listed on this page.
   </label>
</div>

Javascript (with jQuery)

$("#agreeTAC").change(function(){
    var agreed = $(this).is(':checked');
    console.log("agreeTAC value changed and is ", agreed);
    if(agreed === true) { 
       // do 'true' stuff, like enabling a 'Continue' button
    }
    else {
       // do 'false' stuff, like disabling a 'Continue' button
    }
})

$('#uho').attr('checked')将返回undefined。您可以使用$('#uho:checkbox:checked').length属性来检查复选框是否被选中。试试下面的代码片段:

 if ($('#uho:checkbox:checked').length > 0) {
        $.cookie("typpaliva", "Diesel");
   }
   else {
        $.cookie("typpaliva", "Benzin");
   }
  • 在页面加载时使用此代码

    . getelementbyid("# uho")。

使用

  if($('#chkBoxID').is(":checked")){ // do stuff }