gpt4 book ai didi

javascript - 将表单变量传递到 onsubmit 字段?

转载 作者:可可西里 更新时间:2023-11-01 02:37:55 25 4
gpt4 key购买 nike

我正在尝试在发送表单之前验证表单的内容。基本上,我正在尝试处理表单中的数字并确保它们在正确的范围内。问题是我尝试验证它的 JavaScript 认为传递给它的项目是 NaN(我一直在解析它)。

一点工作表明变量(“size”)指的是一个“HTMLInputEleMent”,我猜它确实是 NaN(虽然我不太确定它到底是什么)。我认为问题在于 onSubmit 没有传递我希望它传递的内容,即使我将该字段命名为“size”并且我也传递了 onSubmit“size”。

我试着把它放在引号中,但这只会把它变成一个字符串...

我想知道您是否无法将变量从表单内部传递到它的 onSubmit 字段?是这样吗?如果是这样,我应该怎么做?

这是表格:

        <form onsubmit="return goodForm(size, day, month, year)" action="http://localhost:8080/pomper_servlet/CostCalc" method="GET">              
The day of the month must be entered as a number (ex: 1,22)
<input type="text" name="day"><br>
The month of the year must be entered as a number (ex: Jan.=1, etc.)
<input type="text" name="month"><br>
The year must be entered as a 4 digit number (ex: 2008, 2017)
<input type="text" name="year"><br>
Please Choose a tour-length, in accordance with the chart below:
<input type="TEXT" name="length"><br>
How many people will be in your group? (No More than 10 allowed!)
<input type="text" name="size"><br>
Please select a tour:<br>
<input type="RADIO" name="tour" value="Gardiner Lake">
Gardiner Lake<br>
<input type="RADIO" name="tour" value="Hellroaring Plateau">
Hellroaring Plateau<br>
<input type="RADIO" name="tour" value="The Beaten Path">
The Beaten Path<br>
<input type="SUBMIT" value="Submit">
</form>

这是来自 functions.js 的函数:

function goodForm(gSize, day, month, year) {
"use strict";
window.alert("goodFrame(): "+gSize);
var groupSize1 = parseInt( gSize.replace(/^"|"$/g, ""), 10);
window.alert("goodFrame(): "+groupSize1);
var sizeInt = parseInt(groupSize1);
if(groupSize(sizeInt) && goodDate(day, month, year)){
window.alert("true");
return true;
}
else{
window.alert("false")
return false;
}

那里有对其他功能的引用,但我认为它们与此无关。警报用于调试目的...

提前致谢!

最佳答案

你是这个意思吗?

JavaScript:

 document.getElementById("myForm").onsubmit = function() {
alert(document.getElementById("size").value);
}

HTML:

<form name="myForm" id="myForm">
<input type="text" name="size" id="size">
<input type="submit">
</form>

阐述:

onsubmit 函数附加到 id 为“myForm”的项目,在 HTML 中指定为 id="myForm"。您可以使用文档上的 getElementById 方法查找具有此 ID 的项目。注意不要执行 getElementByID(Id 与 ID)。当您提交表单时,系统会调用此方法,然后您就可以开始了。

然后您可以像查找表单一样查找页面上的项目以获取它们的值。只需给他们一个像 id="size"这样的 ID,您就可以查找它。

你也可以这样做:

alert(document.myForm.size.value);

alert(document.forms["myForm"].size.value);

...但我一直远离这种方法,因为至少在不久之前,一些浏览器讨厌它。也许它现在更好,性能更好,我不确定。

关于javascript - 将表单变量传递到 onsubmit 字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17579605/

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