Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
73
rated 0 times [  79] [ 6]  / answers: 1 / hits: 57160  / 12 Years ago, tue, may 15, 2012, 12:00:00

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 onchange event on field1's input tag. (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 if with null and 'undefined', etc.



Why do the alert boxes pop up if field2 exists ?





function foobar(){

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

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

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

More From » javascript

 Answers
19

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 this and refer to the input field directly. Also, it is clearer to compare to undefined rather than !.



This works:





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


Called like this:





foobar(this.form);

[#85569] Monday, May 14, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
keyanah

Total Points: 642
Total Questions: 93
Total Answers: 114

Location: Virgin Islands (U.S.)
Member since Tue, Jul 7, 2020
4 Years ago
;