[英]JQuery Check if a checkbox is checked checking only working onload
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: 您必须绑定复选框的“ change”事件:
$('#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/ 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. 现在,这种方法的有趣之处在于,它允许以更通用的方式利用changeHandler。 Since you use $(this) instead of $(selector) inside the handler, you can use this function for event delegation, like so: 由于在处理程序中使用$(this)而不是$(selector),因此可以将此函数用于事件委托,如下所示:
$('body').on('change', 'input[type=checkbox]', changeHandler);
This would register the changeHandler to listen to all change-events to checkboxes on the entire page. 这将注册changeHandler来侦听整个页面上复选框的所有更改事件。
<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 />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.