Jquery if checkbox is checked Bootstrap switch

后端 未结 6 1632
情话喂你
情话喂你 2021-01-18 23:13

I use Bootstrap switch plugin to make my checkboxes looks like switch buttons. I need to check if the checkbox is checked in jQuery. I Googled a lot and I tried some advice

相关标签:
6条回答
  • 2021-01-18 23:43
    • use this code on page load

      document.getElementById("#uho").checked = true;

    0 讨论(0)
  • 2021-01-18 23:44

    Demo

    Use .prop() instead of .attr().

    • .prop returns - 'true' or 'false'. Use this
    • .is(':checked') returns - 'true' or 'false' -:checked is a pseudo slector. Or this
    • .attr returns - 'checked' or 'attribute undefined'.

    $('#uho').prop('checked')
    
    if($('#uho').prop('checked')){
        $.cookie("typpaliva", "Diesel");
    }
    else {
        $.cookie("typpaliva", "Benzin");
    }
    
    0 讨论(0)
  • 2021-01-18 23:44

    $('#uho').attr('checked') will return undefined. you can use $('#uho:checkbox:checked').length property to check if checkbox is checked or not. Try this snippet:

     if ($('#uho:checkbox:checked').length > 0) {
            $.cookie("typpaliva", "Diesel");
       }
       else {
            $.cookie("typpaliva", "Benzin");
       }
    
    0 讨论(0)
  • 2021-01-18 23:47

    Use :

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

    instead of

    if ($('#uho').attr('checked')) {
    
    0 讨论(0)
  • 2021-01-18 23:54

    Based on a comment in the accepted answer, here's how I solved this for a Terms and Conditions checkbox in 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
        }
    })
    
    0 讨论(0)
  • 2021-01-19 00:00

    Use

      if($('#chkBoxID').is(":checked")){ // do stuff }
    
    0 讨论(0)
提交回复
热议问题