我正在尝试编写一个非常简单的 jQuery 函数,它有两个主要属性。第一个是检查该字段是否为空。第二个是如果该字段不为空,则执行一个表单,该表单将导致 PHP 编码页面。我对 jQuery 很陌生,如果有人能指出我的错误到底在哪里,我将非常感激。预先感谢您。
function Captcha() {
$('#Button').click(function() {
if ($("#Field").val().length == 0) {
alert("Please fill the box");
return false;
} else {
alert("Your code is saved");
return true;
}
});
}
$(document).ready(function() {
Captcha();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="success.php" id="Alpha" method="post" onsubmit="return Captcha();">
<input id="Field" type="text" placeholder="Enter key here">
<button id="Button" type="submit" form="Alpha">Confirm</button>
</form>
最佳答案
不要使用按钮的 click
事件,而是使用表单的 submit
事件,因为表单可以通过键盘提交,因此可以绕过按钮。
您可以看到工作版本 here (Stack Overflow 阻止提交代码在下面的代码片段环境中工作。)
$(function() {
$('#Alpha').on("submit", function() {
if ($("#Field").val().length == 0) {
alert("Please fill the box");
return false;
} else {
alert("Your code is saved");
return true;
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="success.php" id="Alpha" method="post" onsubmit="return Captcha();">
<input id="Field" type="text" placeholder="Enter key here">
<button id="Button" type="submit" form="Alpha">Confirm</button>
</form>
关于javascript - 如果陈述属实,请提交表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42706018/