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?
Try
or
or
The reason your first code didn’t work is because you were trying to set the
checkedproperty 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 thecheckedattribute using jQuery’sattrfunction which should work too.