Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.checked=true not working with jquery $ function

i want to select a checkbox when a 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 getting selected

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

then i tried:

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

this time the checkbox got selected. why isn't it getting selected with the jquery $ function?

like image 472
Anish Avatar asked Jul 26 '10 12:07

Anish


1 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 were trying to set the checked property on a jQuery object which will have no visible effect as it only works on the native DOM object.

By calling get(0) or accessing the first item [0], we retrieve the native DOM element and can use it normally as in your second example. Alternatively, set the checked attribute using jQuery's attr function which should work too.

like image 124
Anurag Avatar answered Oct 05 '22 14:10

Anurag