仅在选中复选框时提交表单
Submit Form Only When Checkbox is Checked
对于类似于以下示例代码,当用户点击提交时,我如何使用 Jquery 执行以下操作
1)检查复选框是否被选中。
- 如果是,请提交表格。
- 如果没有,显示警告 "Please check the box before submitting the form",取消表单提交。
2)之后,当复选框被选中时,可以提交表单。
<html>
<form>
<input type="checkbox" name="chbox" id="chbox">Check this box before submission
<br>
<input type="submit" value="submit" id="submit">
</form>
</html>
您可以将 required 属性添加到复选框。我建议您也将文本包装在标签中。
<label> <input type="checkbox" name="chbox" id="chbox" required>Check this box before submission </label>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<form id="myForm">
<input type="checkbox" name="chbox" id="chbox">Check this box before submission
<br>
<input type="submit" value="submit" id="submit">
</form>
<script type="text/javascript">
$(function ()
{
$("#myForm").on('submit', function ()
{
if (document.getElementById("chbox").checked)
{
$("#myForm").submit();
}
else
{
e.preventDefault();
alert('Please check the box before submitting the form');
}
});
});
</script>
</body>
</html>
对于类似于以下示例代码,当用户点击提交时,我如何使用 Jquery 执行以下操作 1)检查复选框是否被选中。 - 如果是,请提交表格。 - 如果没有,显示警告 "Please check the box before submitting the form",取消表单提交。 2)之后,当复选框被选中时,可以提交表单。
<html>
<form>
<input type="checkbox" name="chbox" id="chbox">Check this box before submission
<br>
<input type="submit" value="submit" id="submit">
</form>
</html>
您可以将 required 属性添加到复选框。我建议您也将文本包装在标签中。
<label> <input type="checkbox" name="chbox" id="chbox" required>Check this box before submission </label>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<form id="myForm">
<input type="checkbox" name="chbox" id="chbox">Check this box before submission
<br>
<input type="submit" value="submit" id="submit">
</form>
<script type="text/javascript">
$(function ()
{
$("#myForm").on('submit', function ()
{
if (document.getElementById("chbox").checked)
{
$("#myForm").submit();
}
else
{
e.preventDefault();
alert('Please check the box before submitting the form');
}
});
});
</script>
</body>
</html>