简体   繁体   English

javascript表单验证突然停止工作

[英]javascript form validation suddenly stops working

in my code i called a javascript function onsubmit of a form and inside the function making validation to my fields by using formname.fieldname.value and it works fine but suddenly it doesn't work display me an error "formname is not defined". 在我的代码中,我在表单上调用了javascript函数onsubmit,并且在函数内部通过使用formname.fieldname.value对我的字段进行了验证,它工作正常,但突然却无法正常工作,向我显示错误“未定义表单名”。

Thanks in advance 提前致谢

Some possible reasons: 一些可能的原因:

  • you added another object with the same name on that page 您在该页面上添加了另一个具有相同名称的对象
  • you changed the name of the form 您更改了表格的名称
  • the name attribute is no longer there on the form tag 表单标签上不再存在name属性

if you could post your code, that would help, but I think I know what's going on anyway. 如果您可以发布代码,那会有所帮助,但是我想我仍然知道发生了什么。 Inside the onsubmit function, it doesn't have the right variable scope. 在onsubmit函数内部,它没有正确的变量范围。 I usually get around this by passing a reference to the <form> to the function, which is really easy. 我通常通过将对<form>的引用传递给函数来解决此问题,这确实很容易。

<form onsubmit="return doValidation(this);">

and then your javascript: 然后你的JavaScript:

function doValidation(form) {

    form.fieldOne.value = ... // etc

};

The other way would be to reference it absolutely 另一种方法是绝对引用它

<form name="myForm">


function doValidation() {
    var form = document.myForm;
    form.fieldOne.value = ... // etc
}

“formname.fieldname.value” is an IE hack that never should have worked anywhere. “ formname.fieldname.value”是一个IE hack,永远都不应该在任何地方工作。 Don't use it. 不要使用它。 Forms are not supposed to be registered as global variables (window. members), and there are lots of compatibility problems with it, that may have led your script to 'stop' working in some circumstances. 不应将表单注册为全局变量(窗口成员),并且表单存在很多兼容性问题,这可能导致您的脚本在某些情况下“停止”工作。

Given: 鉴于:

<form name="foo" method="get" action="/"> ...
<input name="bar" type="text" value="" />

The correct way to access the input with old-school DOM Level 0 HTML methods is: 使用老式DOM Level 0 HTML方法访问输入的正确方法是:

document.forms.foo.elements.bar

This works across browsers going back to prehistoric Netscape 2 and has a much smaller chance of provoking a name-clash, by using the 'document.forms' array instead of the global 'window' (an object that has many and increasing members whose names you might accidentally choose). 通过使用'document.forms'数组而不是全局'window'(该对象的名称越来越多的成员),跨历史版本的Netscape 2的所有浏览器都可以使用,并且引发名称冲突的可能性要小得多。您可能会不小心选择)。

However these days it is probably easiest to use ID, and DOM Level 1 Core's getElementById method: 但是,如今,使用ID和DOM Level 1 Core的getElementById方法可能最简单:

<form method="get" action="/"> ...
<input name="bar" type="text" value="" id="field-bar" />

document.getElementById('field-bar')

which is simpler and has no clashes with members of the window, document or form objects. 这更简单,并且与窗口,文档或表单对象的成员没有冲突。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM