I am trying to check if a checkbox is checked or not at all times but I'm only getting alerted when the page loads and not at any time when the status has changed.
Here is the code:
<script type="text/javascript">
$(function(){
if ($('#myCheckBox').is(':checked')) {
alert('Yes my checkbox is checked');
} else {
alert('No my checkbox is not checked');
};
});
You have to bind the "change" event of the checkbox:
$('#myCheckBox').change(function() {
if (this.checked) { //if ($(this).is(':checked')) {
alert('Yes my checkbox is checked');
} else {
alert('No my checkbox is not checked');
};
})
When the checkbox will be clicked, the handler will be executed.
Further rading:
try:
$('#myCheckBox').change(function(){
if ($('#myCheckBox').is(':checked')) {
alert('Yes my checkbox is checked');
} else {
alert('No my checkbox is not checked');
};
});
this will call you function every time it's state changes. http://api.jquery.com/change/
have a nice day!
You also need to subscribe to the change-event:
<script type="text/javascript">
$(function(){
var changeHandler = function () {
if ($(this).is(':checked')) {
alert('Yes my checkbox is checked');
} else {
alert('No my checkbox is not checked');
}
};
$('#myCheckbox').change(changeHandler)
.trigger('change');
});
</script>
What it does:
Now, what's interesting about this approach is that it allows the changeHandler to be utilized in a more generic manner. Since you use $(this) instead of $(selector) inside the handler, you can use this function for event delegation, like so:
$('body').on('change', 'input[type=checkbox]', changeHandler);
This would register the changeHandler to listen to all change-events to checkboxes on the entire page.
<script type="text/javascript">
$('#myCheckBox').change(function() {
if ($(this).is(':checked')) {
alert('Yes my checkbox is checked');
} else {
alert('No my checkbox is not checked');
};
});
<script>
$('#myCheckBox').click(function() {
if ($('#myCheckBox').is(':checked')) {
alert('Yes my checkbox is checked');
} else {
alert('No my checkbox is not checked');
};
}
您必须在复选框的onchange中调用上述函数
<input type="checkbox" name="myCheckBox" onchange="callCheckBoxChangeFunction()" value="Bike" /> I have a bike<br />
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.