544

I already tried all the possible ways, but I still didn't get it working. I have a modal window with a checkbox I want that when the modal opens, the checkbox check or uncheck should be based on a database value. (I have that already working with others form fields.) I started trying to get it checked but it didn't work.

My HTML div:

<div id="fModal" class="modal" >
    ...
    <div class="row-form">
        <div class="span12">
            <span class="top title">Estado</span>
             
          <input type="checkbox"  id="estado_cat" class="ibtn">
       </div>
    </div>             
</div>

and the jQuery:

$("#estado_cat").prop( "checked", true );

I also tried with attr, and others seen here in the forums, but none seem to work.
Can someone point me the right way?


EDIT

OK, I'm really missing something here. I can check/uncheck using code if the check box is in the page, but is it's in the modal window, I can't. I tried dozens of different ways.

I have a link that's supposed to open the modal:

<a href='#' data-id='".$row['id_cat']."' class='editButton icon-pencil'></a>

and jQuery to "listen" the click and execute some operations like filling some text boxes with data coming from database. Everything works like I want but the problem is that I can't set checkbox checked/unchecked using code. Help please!

$(function () {
    $(".editButton").click(function () {
        var id = $(this).data('id');
        $.ajax({
            type: "POST",
            url: "process.php",
            dataType: "json",
            data: {
                id: id,
                op: "edit"
            },
        }).done(function (data) {
            // The next two lines work fine,
            // i.e. it grabs the value from database and fills the textboxes
            $("#nome_categoria").val(data['nome_categoria']);
            $("#descricao_categoria").val(data['descricao_categoria']);

            // Then I tried to set the checkbox checked (because it's unchecked by default)
            // and it does not work
            $("#estado_cat").prop("checked", true);
            $('#fModal').modal('show');
        });
        
        evt.preventDefault();
        return false;
    });
});
informatik01
  • 15,174
  • 9
  • 67
  • 100
psopa
  • 5,459
  • 2
  • 11
  • 5
  • what class is applied on modal div when the modal opens ? Also how do you check the database value - Using AJAX or is it already pre-fetched and stored in a variable ? – user1428716 Feb 23 '13 at 19:07
  • set check box after loading modal window I think you are setting the check box before loading the modal window. $('#fModal').modal('show'); $("#estado_cat").attr("checked","checked"); – Vineeth Bhaskaran Mar 10 '14 at 18:00

19 Answers19

905

you have to use the 'prop' function :

.prop('checked', true);

Before jQuery 1.6 (see user2063626's answer):

.attr('checked','checked')
Community
  • 1
  • 1
singe Batteur
  • 9,059
  • 1
  • 9
  • 2
83

Taking all of the proposed answers and applying them to my situation - trying to check or uncheck a checkbox based on a retrieved value of true (should check the box) or false (should not check the box) - I tried all of the above and found that using .prop("checked", true) and .prop("checked", false) were the correct solution.

I can't add comments or up answers yet, but I felt this was important enough to add to the conversation.

Here is the longhand code for a fullcalendar modification that says if the retrieved value "allDay" is true, then check the checkbox with ID "even_allday_yn":

if (allDay)
{
    $( "#even_allday_yn").prop('checked', true);
}
else
{
    $( "#even_allday_yn").prop('checked', false);
}
eriknoyes
  • 839
  • 6
  • 4
  • 50
    Why not just on one single line? `$( "#even_allday_yn").prop('checked', allDay);` – Xavier Hayoz Oct 23 '14 at 14:43
  • 5
    He was trying to demonstrate the possible values. How would you know the real value of the "allDay" without an example like this one here? – Soroush Falahati Jan 30 '17 at 02:00
  • 1
    @Xavier Hayoz. This works if, and only if, allDay returns 'true' or 'false' as a litteral value — not a pure binary one. Checkboxes ar badly designed in html and their checked status can be expressed in very different ways. The safe and only one way I know of is: allDay === 'true' ? $('#even_allday_yn).prop ("checked", true): $('#even_allday_yn).prop ("checked", false). Notice the strict equality operator. – Brice Coustillas Apr 27 '17 at 08:46
  • 1
    `$('#even_allday_yn').prop('checked', allDay === true)` will work because `allDay === true` gives a boolean result. – leftclickben Oct 24 '17 at 08:45
63

Dude try below code :

$("div.row-form input[type='checkbox']").attr('checked','checked')

OR

$("div.row-form #estado_cat").attr("checked","checked");

OR

$("div.row-form #estado_cat").attr("checked",true);
  • 31
    As in KeyOfJ's answer, use `.prop('checked', true)` instead of `attr` - I just ran into the same issue, and `prop` works. – semmelbroesel Oct 16 '13 at 20:45
  • 5
    FYI if you want to make use of the `:checked` pseudo-selector or other native checkbox HTML features, you must use `.prop`. – benastan Nov 14 '13 at 00:57
  • 1
    Tried this and it didn't work but when I changed the code to $("div.row-form #estado_cat").prop("checked","checked"); it did work. (Changed attr to prop). – Jim Evans Mar 04 '14 at 16:01
  • 1
    Unfortunately prop is jQuery 1.6 and higher, so if you are stuck in a legacy framework that won't work for you – wolffer-east Jan 16 '15 at 22:03
  • `.attr()` is the way to go for earlier versions, `.prop()` for jQuery 1.6+. – vapcguy Jul 01 '15 at 19:07
29

"checked" attribute 'ticks' the checkbox as soon as it exists. So to check/uncheck a checkbox you have to set/unset the attribute.

For checking the box:

$('#myCheckbox').attr('checked', 'checked');

For unchecking the box:

$('#myCheckbox').removeAttr('checked');

For testing the checked status:

if ($('#myCheckbox').is(':checked'))

Hope it helps...

shadock
  • 376
  • 3
  • 9
20

Since you are in a modal window (whether dynamic or in the page) you can use the following code to accomplish your goal: (I ran into the same problem on my site and this is how I fixed it)

HTML:

<div class="content-container" style="text-align: right;">
    <input type="checkbox" id="QueryGroupCopyQueries">
    <label for="QueryGroupCopyQueries">Create Copies</label>                                                   
</div>

CODE:

$.each(queriesToAddToGroup, function (index, query) {
    if (query.groupAddType === queriesGroupAddType.COPY) {

        // USE FIND against your dynamic window and PROP to set the value
        // if you are using JQUERY 1.6 or higher.
        $(kendoWindow).find("input#QueryGroupCopyQueries").prop("checked", true);

        return;
    }

In the above "kendoWindow" is my window (mine is dynamic, but I also do this when appending to an element directly in the page). I am looping through an array of data ("queriesToAddToGroup") to see if any rows have an attribute of COPY. If so I want to turn on the checkbox within the window that sets that attribute when a user saves from this window.

KeyOfJ
  • 637
  • 5
  • 13
  • 4
    It should be noted that while other answers to the question at hand may "work", using `prop` as this answer suggests is the CORRECT way of accomplishing dynamic jQuery checkbox checking/un-checking. – Joshua Burns Aug 14 '13 at 23:03
11
.attr("checked",true)
.attr("checked",false)

will work.Make sure true and false are not inside quotes.

user1849310
  • 451
  • 6
  • 10
  • 2
    Attr won't check the checkbox, prop is the one to do the check. Like `.prop('checked', true);` [More info in this Post](http://learn.jquery.com/using-jquery-core/faq/how-do-i-check-uncheck-a-checkbox-input-or-radio-button/) – casivaagustin Oct 08 '14 at 22:08
  • @casivaagustin Depends on the jQuery version. I believe earlier than jQuery 1.6, `.attr()` did work, as described. – vapcguy Jul 01 '15 at 19:09
9

I know this asks for a Jquery solution, but I just thought I'd point out that it is very easy to toggle this in plain javascript.

var element = document.getElementById("estado_cat");
element.checked = true;

It will work in all current and future versions.

Isaac C Way
  • 2,113
  • 2
  • 12
  • 23
5

You can write like below given code.

HTML

<input type="checkbox"  id="estado_cat" class="ibtn">

jQuery

$(document).ready(function(){
    $(".ibtn").click(function(){
        $(".ibtn").attr("checked", "checked");
    });
});

Hope it work for you.

Subir
  • 130
  • 1
  • 3
  • 10
5

If you're wanting to use this functionality for a GreaseMonkey script to automatically check a checkbox on a page, keep in mind that simply setting the checked property may not trigger the associated action. In that case, "clicking" the checkbox probably will (and set the checked property as well).

$("#id").click()
lordcheeto
  • 1,024
  • 11
  • 16
  • Because the checkbox has functionality that goes with it, this is the clean way of setting it as checked and let the associated logic run accordingly. There's a strong case to be made for this to be the accepted answer – Gene Bo Apr 26 '21 at 01:22
4
<body>
      <input id="IsActive" name="IsActive" type="checkbox" value="false">
</body>

<script>
    $('#IsActive').change(function () {
         var chk = $("#IsActive")
         var IsChecked = chk[0].checked
         if (IsChecked) {
          chk.attr('checked', 'checked')
         } 
         else {
          chk.removeAttr('checked')                            
         }
          chk.attr('value', IsChecked)
     });
</script>
reza akhlaghi
  • 658
  • 1
  • 8
  • 19
3
$("#divParentClip").find("#subclip_checkbox")[0].checked=true;

Find will return array , so use [0] to get even if there is only one item

if you don't use find then

$("#subclip_checkbox").checked=true;

this worked fine in Mozilla Firefox for me

Harry
  • 80,224
  • 23
  • 168
  • 185
Arvin
  • 796
  • 3
  • 10
  • 32
  • 1
    This works, all other solutions doesn't get detected if you have a :checked style in your css – bhappy Nov 04 '15 at 19:05
3

Worked for me:

$checkbok.prop({checked: true});
Sergio Pulgarin
  • 760
  • 6
  • 19
2

Try this since your are using jQuery UI probably (if not please comment)

 $("#fModal" ).dialog({
     open: function( event, ui ) {

     if(//some hidden value check which stores the DB value==expected value for
      checking the Checkbox)

         $("div.row-form input[type='checkbox']").attr('checked','checked');

    }
   });
user1428716
  • 1,920
  • 1
  • 16
  • 32
2

Have you tried running $("#estado_cat").checkboxradio("refresh") on your checkbox?

Undo
  • 25,204
  • 37
  • 102
  • 124
J2N
  • 291
  • 4
  • 18
2

This works.

 $("div.row-form input[type='checkbox']").attr('checked','checked');
Deepu
  • 11,425
  • 13
  • 53
  • 87
Chetan Patel
  • 129
  • 12
2

This occurs because you with the newest version of jquery attr('checked') returns 'checked' while prop('checked') returns true.

ann
  • 584
  • 1
  • 9
  • 19
Rohan
  • 3,148
  • 1
  • 27
  • 35
2

I encountered this problem too.

and here is my old doesn't work code

if(data.access == 'private'){
     Jbookaccess.removeProp("checked") ; 
    //I also have tried : Jbookaccess.removeAttr("checked") ;
 }else{
    Jbookaccess.prop("checked", true)
}

here is my new code which is worked now:

if(data.access == 'private'){
     Jbookaccess.prop("checked",false) ;
 }else{
    Jbookaccess.prop("checked", true)
}

so,the key point is before it worked ,make sure the checked property does exist and does not been removed.

Eddy
  • 2,839
  • 31
  • 37
1

Set the check box after loading the modal window. I think you are setting the check box before loading the page.

$('#fModal').modal('show');
$("#estado_cat").attr("checked","checked");
Danilo Piazzalunga
  • 6,909
  • 5
  • 43
  • 65
Vineeth Bhaskaran
  • 1,801
  • 1
  • 26
  • 31
0
<div class="custom-control custom-switch">
      <input type="checkbox" class="custom-control-input" name="quiz_answer" id="customSwitch0">
      <label class="custom-control-label" for="customSwitch0"><span class="fa fa-minus fa-lg mt-1"></span></label>
  </div>

Remember to increment the the id and for attribute respectively. For Dynamically added bootstrap check box.

$(document).on('change', '.custom-switch', function(){
    let parent = $(this);
    parent.find('.custom-control-label > span').remove();
    let current_toggle = parent.find('.custom-control-input').attr('id');
    if($('#'+current_toggle+'').prop("checked") == true){
        parent.find('.custom-control-label').append('<span class="fa fa-check fa-lg mt-1"></span>');
    }
    else if($('#'+current_toggle+'').prop("checked") == false){
        parent.find('.custom-control-label').append('<span class="fa fa-minus fa-lg mt-1"></span>');
    }
})