【问题标题】:Passing a form-variable into the onsubmit field?将表单变量传递到 onsubmit 字段?
【发布时间】:2013-07-08 21:53:13
【问题描述】:

我正在尝试在发送表单之前验证其内容。基本上,我正在尝试使用表格中的数字并确保它们在正确的范围内。问题是我试图验证它的 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;
}

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

提前致谢!

【问题讨论】:

  • 您能在 onsubmit 方法中按 ID 查找字段吗?
  • 呃...也许-我该怎么做(我对此很陌生,以防还不清楚...)
  • 见下面的答案。我会详细说明。

标签: javascript forms nan onsubmit


【解决方案1】:

如果您不想使用 JQuery:

你不需要传递参数,试着给它们一个id,然后在好表单函数中通过它们的id获取它们。

function goodForm() {
    var size = document.getElementById("size");
    if(null != size){
       // do something with size.value
    }

}

【讨论】:

    【解决方案2】:

    您可以尝试将每个输入(日、月、年、大小)赋予 id(您可以使用与 name 属性相同的值)。 在 goodForm() 函数中通过 id 获取值。

    &lt;input type="text" name="day" id="day"&gt;

    document.getElementById("some id").value

    【讨论】:

      【解决方案3】:

      首先,像这样(通过 onsubmit)进行内联验证是不好的形式。通常你会想要做事件绑定,我将包含使用 jQuery 的示例代码,但你也可以使用其他方法。

      首先,为您的表单指定页面的唯一 ID 属性。我假设&lt;form id="MyForm"...

      接下来,您可能希望您的验证方法“了解”它需要的字段。

      //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 &lt= today) return false;
      
              //passed checks
              return true;
          }
      });

      【讨论】:

        【解决方案4】:

        你的意思是这样的吗?

        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 vs ID)。当您提交表单时,此方法将被调用,然后您就可以上路了。

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

        你也可以这样做:

        alert(document.myForm.size.value);
        

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

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

        【讨论】:

          猜你喜欢
          • 2011-03-19
          • 2020-03-29
          • 1970-01-01
          • 2011-03-24
          • 1970-01-01
          • 2011-07-14
          • 1970-01-01
          • 1970-01-01
          • 2018-01-01
          相关资源
          最近更新 更多