.checked = true does not work with jquery $ function

I want to check the box when the button is clicked.

<form action="" method="post" id="form2">
    <input type="checkbox" id="checkone" value="one" name="one" />
    <input type="button" value="Click me" id="buttonone"/>
</form>

when I tried the following, the checkbox was not selected.

$('#buttonone').click(function() {
    $('#checkone').checked=true;
});

then I tried:

$('#buttonone').click(function() {
    document.getElementById('checkone').checked=true;
});

This time the checkbox is checked. why is it not selectable using jquery $ function?

+5
source share
7 answers

Try

$('#checkone').attr('checked', true);

or

$('#checkone').get(0).checked = true;

or

$('#checkone')[0].checked = true; // identical to second example

The reason your first code didn't work is because you tried to set a property checkedon a jQuery object that would not have a visible effect, since it only works on its own DOM object.

get(0) [0], DOM . , checked, jQuery attr, .

+11

.attr() jQuery, :

$('#buttonone').click(function() {
  $('#checkone').attr('checked', true);
});

DOM, :

$('#buttonone').click(function() {
  $('#checkone')[0].checked = true; //get the DOM element, .checked is on that
});

, jQuery:

document.getElementById('buttonone').onclick = function() {
  document.getElementById('checkone').checked = true;
};
+2

, :

<div id="group-one">
  <input type="radio" name="groups" value="1" checked="checked" />
  <input type="radio" name="groups" value="2" />
</div>
<div id="group-two">
  <input type="radio" name="groups" value="1" checked="checked" />
  <input type="radio" name="groups" value="2" />
</div>

Javascript (). include HTML . , .

jsfiddle, , checked, :

http://jsfiddle.net/bozdoz/5ecq8/

, , , , -, : id name , .

+1

Try

$('#checkone').attr('checked', true);

DOM, jQuery ($(selector) - ). , .

0

$('#checkone').attr('checked', true);

googling "jquery check checkbox"

0

$('#buttonone').click(function() {
    $('#checkone')[0].checked=true;
});

This is because ".checked" is not part of jQuery, and you are trying to use it in a jQuery object. If you index the jQuery object at [0], you get a raw Javascript object that ".checked" exists.

More details here: http://phrappe.com/javascript/convert-a-jquery-object-to-raw-dom-object/

0
source

try it

    $('#buttonone').click(function() {
  $('#checkone').prop('checked', true);
});
0
source

All Articles