gpt4 book ai didi

javascript - 为什么onsubmit函数好像没有执行?

转载 作者:行者123 更新时间:2023-11-30 08:57:17 25 4
gpt4 key购买 nike

我不知道我做错了什么。 validateForm() 似乎不是从 onsubmit 执行的。这是 validateForm()

function validateForm() {
var amt = IsNumeric(document.forms["InvGenPay"]["Amount"].value);

alert(amt);

if (amt == false)
{
alert("placeholder to avoid scrolling.");
return false;
}
else
{
return true;
}
}

function IsNumeric(strString)
{
// check for valid numeric strings
var strValidChars = "0123456789.";
var strChar;
var blnResult = true;

if (strString.length == 0) return false;

// test strString consists of valid characters listed above
for (i = 0; i < strString.length && blnResult == true; i++)
{
strChar = strString.charAt(i);
if (strValidChars.indexOf(strChar) == -1)
{
blnResult = false;
}
}

if (0 > parseFloat(strString))
{
return false;
}
else
{
return blnResult;
}
}

这是带有 onsubmit 的表单:

<script type="text/javascript" language="JavaScript1.2">
document.write('<form name="InvGenPayDonation" action="'+PostURL+'" onsubmit="return validateForm();" method="POST">');
</script>


<input type='text' name='DonationAmount' value="0.00">
In honor of <span style="color: #FF0000"><br />
<input type='text' name='TransDesc' id='TransDesc' value="" >
<input type="submit" value="Next">
</form>

最佳答案

您最大的问题是您的验证代码中没有正确的表单名称(或与此相关的正确字段名称)。

var amt = IsNumeric(document.forms["InvGenPay"]["Amount"].value);

对比

'<form name="InvGenPayDonation" action="'+PostURL+'" 

完整的工作代码:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"         
"http://www.w3.org/TR/html4/strict.dtd">
<head>
<title>Sampe file</title>

<script>
function validateForm() {
// Badly named variable, since this is actually a boolean of 'IsNumeric'
var amt = IsNumeric(document.forms["InvGenPayDonation"]["DonationAmount"].value);


// Can be simplified as simply:
//return amt;
alert('Amt = ' + amt);

if (!amt)
{
alert("placeholder to avoid scrolling.");
return false;
}
else
{
return true;
}
}

function IsNumeric(n) {
// Shamelessly stolen from:
// http://stackoverflow.com/questions/18082/validate-numbers-in-javascript-isnumeric
return !isNaN(parseFloat(n)) && isFinite(n);
}

</script>

<body>
<form name="InvGenPayDonation" action="#"
onsubmit="return validateForm();"
method=POST>


<input type='text' name='DonationAmount' value="0.00">
In honor of <span style="color: #FF0000"><br />
<input type='text' name='TransDesc' id='TransDesc' value="" >
<input type="submit" value="Next">

<script>
// Assigned for testing purposes
var PostURL = "#"
document.forms.InvGenPayDonation.action = PostURL;
</script>
</form>
</body>
</html>

关于javascript - 为什么onsubmit函数好像没有执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12396219/

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