JQuery if checked.

I use the Switch Bootstrap plugin to make my checkboxes look like toggle buttons. I need to check if the checkbox is checked in jQuery. I searched a lot and I tried some tips and code snippets, but to no avail.

I think the cleanest code I found is

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

but it still does not work on my site. I declared jQuery in the head. I am trying to use these snippets on checkboxes other than bootstrap-switch-checkbox, but still to no avail.

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"/>
+4
source share
6 answers

Using:

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

instead

if ($('#uho').attr('checked')) {
+6
source

Demo

Use instead . .prop().attr()

  • .prop - 'true' 'false'.
  • .is(':checked') - 'true' 'false' - :checked .
  • .attr - 'checked' 'attribute undefined'.

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

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

$('#uho').attr('checked') undefined. $('#uho:checkbox:checked').length, , . :

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

0

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

, , :

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
    }
})
0

Source: https://habr.com/ru/post/1545025/


All Articles