Javascript 检查表单输入是否存在

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10603644/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 02:05:26  来源:igfitidea点击:

Check if a form input exists

javascript

提问by Nigel Ridley

I want to check if an input tag named "field2" exists when the user is filling out input name "field1". I do that by executing a JavaScript function using the onchangeevent on field1's inputtag. (I'm testing using alert boxes.) If field2 does not exist, JavaScript clicks a button and the form is updated to have both field1 and field2. But the alert box pops up even when field2 exists no matter which of the 3 methods I use. I tried all sorts of combinations using ifwith nulland 'undefined', etc.

当用户填写输入名称“field1”时,我想检查是否存在名为“field2”的输入标签。我通过使用onchangefield1input标签上的事件执行 JavaScript 函数来做到这一点。(我正在使用警告框进行测试。)如果 field2 不存在,JavaScript 将单击一个按钮,表单将更新为同时包含 field1 和 field2。但是,无论我使用 3 种方法中的哪一种,即使 field2 存在,警报框也会弹出。我尝试了使用ifwithnull'undefined'等的各种组合。

Why do the alert boxes pop up if field2 exists ?

如果 field2 存在,为什么会弹出警告框?

function foobar(){

if(!document.getElementsByName("field2"){
alert("foobar");
}

if(!document.forms[0].field2){
alert("foobar");
}

if(!document.forms[0].elements.namedItem("field2"){
alert("foobar");
}
}

采纳答案by Nigel Ridley

Actually, the problem was that the page had various forms and therefore forms[0]was not referring to the form I wanted. So I think the best way is to use thisand refer to the inputfield directly. Also, it is clearer to compare to undefinedrather than !.

实际上,问题在于页面有多种形式,因此forms[0]不是指我想要的形式。所以我认为最好的方法是直接使用this和引用该input字段。此外,比较与undefined而不是更清楚!

This works:

这有效:

function foobar(fooform){
    if (fooform.field2 === undefined) {
        alert("foobar");
    }
}

Called like this:

像这样调用:

foobar(this.form);

回答by Amberlamps

You are missing a bracket: if(!document.getElementsByName("field2"))

你缺少一个括号: if(!document.getElementsByName("field2"))

回答by GeneCode

Just to update since using getElementsByName and compare to null doesn't work properly anymore. What works now is checking the length of the element.

只是为了更新,因为使用 getElementsByName 并与 null 比较不再正常工作。现在有效的是检查元素的长度。

if(document.getElementsByName("field2").length<=0) {
  // then field2 does not exist
}

回答by Debbie Kurth

var element = document.getElementsByName("field2");
if(typeof(element) == 'undefined' && element != null)
{
// Field exists
}
else
{
// then field does not exist
}