简体   繁体   中英

jquery set and remove checked attribute doesn't work, javascript does

for clarity, let's say that I have a checkbox that I want to check and uncheck using two buttons.

I can check/uncheck the box using basic javascript, but with jquery, as soon as I remove the attribute, I cannot set it back... Any idea why?

I created a basic fiffle to illustrate:

http://jsfiddle.net/2K244/

<button id='button1'>check</button>
<button id='button2'>uncheck</button>
<input type="checkbox" id="myBox1" value="polo" />
<br/>
<button id='button3'>check</button>
<button id='button4'>uncheck</button>
<input type="checkbox" id="myBox2" value="polo" />
<br/>

$(document).ready(function () {
    $('#button1').click(function () {
        $('#myBox1').attr('checked','checked');
    });
    $('#button2').click(function () {
        $('#myBox1').removeAttr('checked');
    });
    $('#button3').click(function () {
        document.getElementById('myBox2').checked = true;
    });
    $('#button4').click(function () {
        document.getElementById('myBox2').checked = false;
    });

});

You should be using .prop() instead. From jQuery's documentation on .attr() :

As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method.

You should use .prop() now.

http://jsfiddle.net/2K244/1/

$('#button1').click(function () {
    $('#myBox1').prop('checked',true);
});
$('#button2').click(function () {
    $('#myBox1').prop('checked', false);
});
$('#button3').click(function () {
    $('#myBox2').prop('checked', true);
});
$('#button4').click(function () {
    $('#myBox2').prop('checked', false);
});

to uncheck a box, use the prop function. $('#myBox1').prop('checked', false); without quotes on false

I don't understand why yours isn't working, but use this:

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

$("#myBox1").prop("checked",false);

Make sure to have a recent version of jQuery.

The status of the checked state can be modified using the true || false second parameter in the .prop() method.

$('#btn_checked').on('click', function() {
     $('#myBox1').prop('checked', true);
});

$('#btn_unchecked').on('click', function() {
     $('#myBox1').prop('checked', false);
});

jsFiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM