如何在点击提交时检查是否选中了复选框? 我希望它在未选中此框时显示警告。
$('#submit').on('click', function() {
if($('#terms').is(':checked')) {
}
else {
alert("To proceed you must accept the terms.")
}
});
答案 0 :(得分:2)
如果未选中该复选框,您似乎要停止提交表单。无论您的功能结果如何,您的代码仍将提交表单。您需要做的是将输入放入<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;
}
}
答案 1 :(得分:1)
将其打包在$(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.")
}
});
});
答案 2 :(得分:0)
您的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
函数。