javascript 将表单变量传递到 onsubmit 字段?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17579605/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Passing a form-variable into the onsubmit field?
提问by Jo.P
I am trying to verify the contents of a form before sending it. Basically, I'm trying to work with the numbers in the form and ensure they are within the correct range. The problem is that the JavaScript I have which is trying to verify it thinks that the item being passed to it is NaN (I have been parsing it).
我试图在发送之前验证表单的内容。基本上,我正在尝试处理表单中的数字并确保它们在正确的范围内。问题是我试图验证它的 JavaScript 认为传递给它的项目是 NaN(我一直在解析它)。
A little work revealed that the variable ("size") is referring to an "HTMLInputEleMent", which I guess is, indeed, NaN (although I am not quite sure what it actually is). I think that the problem is that the onSubmit is not passing what I want it to be passing, even though I named the field "size" and I passed onSubmit "size" too.
一些工作表明变量(“size”)指的是“HTMLInputEleMent”,我猜它确实是 NaN(虽然我不太确定它实际上是什么)。我认为问题在于 onSubmit 没有传递我希望它传递的内容,即使我将字段命名为“size”并且我也传递了 onSubmit“size”。
I tried putting it in quotation marks, but that just turns it into a string...
我试着把它放在引号中,但这只是把它变成了一个字符串......
I am wondering if perhaps you are unable to pass a variable from WITHIN the form to it's onSubmit field? Is that so? If so, how should I do this?
我想知道您是否无法将表单内的变量传递给它的 onSubmit 字段?是这样吗?如果是这样,我该怎么做?
Here is the form:
这是表格:
<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>
And here is the function, from functions.js:
这是来自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;
}
There are references to other functions in there, but they aren't relevant to this, I think. The alerts were/are for debugging purposes...
那里有对其他函数的引用,但我认为它们与此无关。警报是/用于调试目的...
Thanks in advance!
提前致谢!
采纳答案by Tsikon
You can try giving each one of the Inputs (day, month, year, size) to id (you can use the same value as your name attribute).
Get the value by id within your goodForm()
function.
您可以尝试将每个输入(日、月、年、大小)都赋予 id(您可以使用与名称属性相同的值)。在您的goodForm()
函数中通过 id 获取值。
<input type="text" name="day" id="day">
<-- set
<input type="text" name="day" id="day">
<-- 设置
document.getElementById("some id").value
<-- get
document.getElementById("some id").value
<-- 得到
回答by oooyaya
Is something like this what you mean?
你的意思是这样的吗?
JavaScript:
JavaScript:
document.getElementById("myForm").onsubmit = function() {
alert(document.getElementById("size").value);
}
HTML:
HTML:
<form name="myForm" id="myForm">
<input type="text" name="size" id="size">
<input type="submit">
</form>
Elaboration:
细化:
The onsubmit function is attached to an item whose id is "myForm" specified in the HTML as id="myForm". You can lookup the item with this ID using the method getElementById on the document. Careful not to do getElementByID (Id vs ID). When you submit the form, this method will get called and you'll be on your way.
onsubmit 函数附加到 id 为“myForm”的项目,在 HTML 中指定为 id="myForm"。您可以使用文档上的 getElementById 方法查找具有此 ID 的项目。小心不要执行 getElementByID (Id vs ID)。当您提交表单时,此方法将被调用,您就可以开始了。
Then you can lookup items on the page to get their value the same way you looked up the form. Just give them an ID like id="size" and you can look it up.
然后,您可以在页面上查找项目,以与查找表单相同的方式获取它们的值。只需给他们一个像 id="size" 这样的 ID,你就可以查到它。
You can also do something like:
您还可以执行以下操作:
alert(document.myForm.size.value);
or
或者
alert(document.forms["myForm"].size.value);
...but I've stayed away from that method since, a while ago at least, some browsers hated it. Maybe it's better and more performant now, I'm not sure.
...但我一直远离这种方法,因为至少在不久之前,一些浏览器讨厌它。也许它现在更好,性能更高,我不确定。
回答by Tracker1
First, doing inline validation like this (via onsubmit) is bad form. Usually you will want to do event binding, I'm going to include sample code using jQuery, but you can use other methods as well.
首先,像这样(通过 onsubmit)进行内联验证是不好的形式。通常您会想要进行事件绑定,我将使用 jQuery 包含示例代码,但您也可以使用其他方法。
First, give your form a unique ID attribute for the page. I'm assuming <form id="MyForm"...
首先,为您的表单指定页面的唯一 ID 属性。我假设<form id="MyForm"...
Next, you will likely want your validation method to "know" about the fields it needs.
接下来,您可能希望验证方法“知道”它需要的字段。
//this function is executed when the page's dom is loaded
// assumes jQuery is loaded already
$(function(){
//binds the myFormOnSubmit method below to run as part of your form's onsubmit method
$('#MyForm').submit(myFormOnSubmit);
//runs when the form is trying to submit
function myFormOnSubmit(event) {
var f = $(this);
// note, you have to match on attribute selectors
// you may want to give each of these fields an id=".." attribute as well to select against #IdName
var size = f.find('[name=size]').val();
var day = f.find('[name=day]').val();
var month = f.find('[name=month]').val();
var year = f.find('[name=year]').val();
var tour = f.find('[name=tour]:checked').val(); //selected radio button's
var isValid = validDate(year,month,day) && validSize(gSize) && validTour(tour);
if (!isValid) {
event.preventDefault(); //stop submit
}
}
function validTour(tour) {
return !!tour; //will be false if it's an empty string, ex: no selected value
}
function validSize(size) {
var s = parseInt(size); //get integer value for size
if (s <= 0 || s > 10) return false; //not in range
if (s.toString() !== size) return false; //doesn't match input, invalid input
return true; //true
}
function validDate(year, month, day) {
//coerce the values passed into numbers
var y = +year, m = +month, d = +day;
//convert to an actual date object
var dtm = new Date(y, --m, d);
//compare the values
if (!dtm) return false; //invalid input
if (dtm.getFullYear().toString() !== year.toString()) return false; //year doesn't match input
if ((dtm.getMonth() + 1).toString() !== month.toString()) return false; //month doesn't match input
if (dtm.getDate().toString() !== day.toString()) return false; //day doesn't match input
var now = new Date(); console.log(now);
var today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
//entered date is before today, invalid
if (dtm <= today) return false;
//passed checks
return true;
}
});
回答by ia.solano
In case you don't want to use JQuery:
如果您不想使用 JQuery:
You don't need to pass the parameters, try giving them an id and get them by their id inside the good form function.
您不需要传递参数,尝试给它们一个 id 并通过它们在 good form 函数中的 id 获取它们。
function goodForm() {
var size= document.getElementById("size").value;
if(size...){
...
}
}