I have a javascript function that sets a variable everytime a checkbox is clicked:
function handleClick(cb) {
alert('entered function');
setTimeout(function () {
if (cb.checked ) {
$("#IsChecked").val('true');
}
else
$("#IsChecked").val('false');
alert('now my value is: '+ $("#IsChecked").val());
}, 0);
}
Heres my checkbox:
<input id="MyCheckBox" type="checkbox" value="true" onclick="handleClick(this);"
name="MyCheckBox" checked="checked">
This works great everytime the checkbox is checked. But now i need to know if the checkbox is checked when the user clicks a button and has never touched the checkbox before. So i do this:
$(document).ready(function () {
$("#IsChecked").val('default');
$('#btnCheck').click(function (e) {
var isComplete = $("#IsChecked").val();
if (isComplete == 'default') {
var cb = $('#MyCheckBox');
handleClick(cb);
alert('after handleClick ischecked is: ' + $("#IsChecked").val());
}
});
});
When i click my button and the checkbox is checked by default, i get these alerts in this order:
entered function
after handleClick ischecked is: default
now my value is: false
If i check the checkbox to toggle it, i get these alerts as expected:
entered function
now my value is: false
In my handleClick event, the setTimeout is there because of IE so i cant get rid of it. How can i check to see if a checkbox is checked without having to click the checkbox itself? Thanks
You can find out if checkbox is checked in javascript with click event by using val() method