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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Jquery if复选框是否已选中Bootstrap开关相关的知识,希望对你有一定的参考价值。

我使用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"/>
答案

使用 :

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

代替

if ($('#uho').attr('checked')) {
另一答案

Demo

使用.prop()而不是.attr()

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

.attr
另一答案

$('#uho').prop('checked') if($('#uho').prop('checked')){ $.cookie("typpaliva", "Diesel"); } else { $.cookie("typpaliva", "Benzin"); } 将返回undefined。您可以使用$('#uho').attr('checked')属性来检查是否选中了复选框。试试这个片段:

$('#uho:checkbox:checked').length
另一答案
  • 在页面加载时使用此代码 document.getElementById(“#uho”)。checked = true;
另一答案

使用

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

根据已接受答案中的评论,以下是我在bootstrap中为条款和条件复选框解决此问题的方法:

HTML

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

javascript(使用jQuery)

<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>

以上是关于Jquery if复选框是否已选中Bootstrap开关的主要内容,如果未能解决你的问题,请参考以下文章

jquery判断复选框是否选中

[jQuery] 判断复选框是否选中

jQuery判断checkbox是否选中的3种方法

jquery怎么判断某一个复选框是不是被选中啊?

jqueryjs判断复选框是否选中

jQuery 单选框 选中问题