gpt4 book ai didi

javascript - 返回 false 被 onsubmit 忽略

转载 作者:行者123 更新时间:2023-12-02 16:54:27 24 4
gpt4 key购买 nike

我花了几个小时来解决这个问题,所以当发现这只是错误位置的单引号或其他东西时,我会感到沮丧。

我正在制作一个基本的 HTML 页面来测试基本的验证表单输入。如果我在 validateForm() 函数的开头删除 return false,它会按预期工作。但是,如果它在验证循环内(如下所示),则它不起作用并且表单会提交。 (hello.php 仅输出 hello world)。

此处的所有诊断警报均按预期运行...包括 return-false 之前的警报。 (当我将输入留空时)。

我觉得我错过了一些非常明显的东西,但无法弄清楚它是什么。

<?php 
echo <<<END
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<title>Test</title>

<script type="text/javascript">
$(document).ready(function(){
$("input").focus(function(){
$(this).css("background-color","#cccccc");
});
$("input").blur(function(){
$(this).css("background-color","#ffffff");
});
});

function validateForm() {
alert("Validating");
$("form[name=queryForm]").find(":input[type=text]").each(function() {
alert("Checking " + $(this).attr('name'));
if($(this).val()==null || $(this).val()=="") {
$(this).val('REQUIRED');
$(this).css("background-color","#ffbbbb");
alert($(this).attr('name') + ' must not be left blank.');
return false;
}
}); // end of the each function
}
</script>
</head>
<body>
<form name="queryForm" action="hello.php" onsubmit="return validateForm();" method="post">
<input type="text" name="First Name"><br>
<input type="text" name="Last Name">
<input type="submit" value="Submit">
</form>
</body>
</html>
END;
?>

最佳答案

在 .each() 中使用 return 不会得到所需的结果。

试试这个:

function validateForm() {
alert("Validating");
var result = true;
$("form[name=queryForm]").find(":input[type=text]").each(function() {
alert("Checking " + $(this).attr('name'));
if($(this).val()==null || $(this).val()=="") {
$(this).val('REQUIRED');
$(this).css("background-color","#ffbbbb");
alert($(this).attr('name') + ' must not be left blank.');
result =false;
return false; //break the each()
}
}); // end of the each function
return result;
}

关于javascript - 返回 false 被 onsubmit 忽略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26289649/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com