【发布时间】:2017-06-24 03:14:20
【问题描述】:
如何检查单击提交时是否选中了复选框? 我希望它在未选中该框时显示警报。
$('#submit').on('click', function() {
if($('#terms').is(':checked')) {
}
else {
alert("To proceed you must accept the terms.")
}
});
【问题讨论】:
如何检查单击提交时是否选中了复选框? 我希望它在未选中该框时显示警报。
$('#submit').on('click', function() {
if($('#terms').is(':checked')) {
}
else {
alert("To proceed you must accept the terms.")
}
});
【问题讨论】:
您的 JSFiddle 不起作用的原因是您需要等到文档加载完毕后再附加事件处理程序。否则,jQuery 会在提交按钮存在之前寻找它。
要确保按钮已加载,请使用$(document).ready():
$(document).ready(function() {
$('#submit').on('click', function() {
if($('#terms').is(':checked')) {
}
else {
alert("To proceed you must accept the terms.")
}
});
});
请注意,您已经有一个额外的右大括号和括号(这是一个语法错误),它现在关闭了 $(document).ready 函数。
【讨论】:
看起来您想要做的是在未选中复选框的情况下停止提交表单。无论函数的结果如何,您的代码仍将提交表单。您需要做的是将输入放入<form> 标记中,并为onsubmit 事件添加处理程序,这将取消表单提交。
HTML:
<form onsubmit="return check_checkbox()">
<input type="checkbox" id="terms" unchecked/>Terms
<br /><br />
<button id="submit">
continue
</button>
</form>
Javascript:
function check_checkbox()
{
if($('#terms').is(':checked')) {
return true;
} else {
alert("To proceed you must accept the terms.");
return false;
}
}
【讨论】:
将其包裹在$(document).ready(function(){}); 中并使用.prop()
$(document).ready(function(){
$('#submit').on('click', function() {
if($('#terms').prop('checked')==true) {
}
else {
alert("To proceed you must accept the terms.")
}
});
});
【讨论】: