Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery if checkbox is checked Bootstrap switch

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 and code snippets but without success.

I think the cleanest code I found is

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

but it still wont work on my website. I have declared jQuery in head. I try to use this snippets on non-bootstrap-switch-checkboxes but still no success.

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"/>
like image 624
user3690515 Avatar asked Jun 18 '14 06:06

user3690515


2 Answers

Use :

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

instead of

if ($('#uho').attr('checked')) {
like image 200
Bhushan Kawadkar Avatar answered Oct 22 '22 17:10

Bhushan Kawadkar


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");
}
like image 33
Shaunak D Avatar answered Oct 22 '22 16:10

Shaunak D