Jquery if复选框是否已选中Bootstrap开关

时间:2014-06-18 06:30:37

标签: javascript jquery twitter-bootstrap checkbox

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

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

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

但它仍然无法在我的网站上运行。我已经声明了jQuery。我尝试在非bootstrap-switch-checkboxes上使用这个片段,但仍然没有成功。

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> 

HTML

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

6 个答案:

答案 0 :(得分:9)

<强> Demo

使用 .prop() 代替.attr()

  • .prop返回 - &#39; true&#39;或者&#39; false&#39;。 使用此
  • .is(':checked')返回 - &#39; true&#39;或者&#39; false&#39; - :checked是伪滑块。 或者
  • .attr返回 - &#39;已检查&#39;或者&#39;属性未定义&#39;。

$('#uho').prop('checked')

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

答案 1 :(得分:7)

使用:

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

而不是

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

答案 2 :(得分:0)

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

 if ($('#uho:checkbox:checked').length > 0) {
        $.cookie("typpaliva", "Diesel");
   }
   else {
        $.cookie("typpaliva", "Benzin");
   }

答案 3 :(得分:0)

  • 在页面加载时使用此代码

    document.getElementById(“#uho”)。checked = true;

答案 4 :(得分:0)

使用

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

答案 5 :(得分:0)

根据已接受答案中的评论,以下是我在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(使用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
    }
})