Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a form input exists

Tags:

javascript

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");
}
}
like image 992
Nigel Ridley Avatar asked May 15 '12 15:05

Nigel Ridley


People also ask

How can check input value or not in jQuery?

Answer: Use the jQuery val() Method You can use the val() method to test or check if inputs are empty in jQuery.

How to check if a button exists in jQuery?

Answer: Use the jQuery . length Property You can use the jQuery . length property to determine whether an element exists or not in case if you want to fire some event only if a particular element exists in DOM. Here's an example that displays an alert on button click if the specified element exists.


1 Answers

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

like image 125
Amberlamps Avatar answered Sep 17 '22 21:09

Amberlamps