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
$('#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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With