繁体   English   中英

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

[英]Jquery if checkbox is checked Bootstrap switch

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

我认为我发现的最干净的代码是

$('#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"/>

演示

使用.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");
}

采用 :

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

代替

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

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

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

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

采用

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM