我想创建一个警报,当我的复选框中的选项都没有显示时显示。
<script>
function mFunction () {
if (!!this.form.checkbox.checked) {
alert('not checked');
return false;
}
};
</script>
上面的js
<body>
<form>
<input type="checkbox" name="choice1" value="choice1" id="confirm">choice 1<br>
<input type="checkbox" name="choice2" value="choice2" >choice 2<br>
<input type="checkbox" name="choice3" value="choice3">choice 3<br><br>
<input type="submit" value="Submit" onclick="mFunction()">
</form>
如果没有选择,我想要一个警报,如果选择了一些东西,则没有警报。
最佳答案
你可以通过以下方式检查
[...document.querySelectorAll("input[type='checkbox']")].some(i=>i.checked)
function mFunction (e)
{
if(![...document.querySelectorAll("input[type='checkbox']")].some(i=>i.checked))
{
alert('not checked');
e.preventDefault();
}
};
function checkForm(t,e) {
e.preventDefault();
console.log('checked');
};
<form onsubmit="checkForm(this,event);">
<input type="checkbox" name="choice1" value="choice1" id="confirm">choice 1<br>
<input type="checkbox" name="choice2" value="choice2" >choice 2<br>
<input type="checkbox" name="choice3" value="choice3">choice 3<br><br>
<input type="submit" value="Submit" onclick="mFunction(event)">
</form>
关于多选复选框的 Javascript 验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55483649/