faqts : Computers : Programming : Languages : JavaScript : Forms

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

104 of 112 people (93%) answered Yes
Recently 7 of 10 people (70%) answered Yes

Entry

How will I know if a certain element in a form exists given the element name?

Feb 19th, 2002 01:53
suresh kc, Jo Chua, Suresh KC


Say you were looking for a form element "field1"
you could well.. use a function where you can either go through all
the form objects and check for the one you are looking for like this
//where x is the name of the form
for (o in document.x) {
    if(o == "field1")
	alert(o +" found");
}
OR
you could directly try to evaluate that element, if it exists 
it will return an object otherwise it will return undefined
var exists = eval(document.x["field1"]);
if(exists)
    alert("true");
}
sample html file
----------------
<html>
<script language="Javascript">
function e(){
//first way
    for (o in document.x)
        if(o == "field1")
	    alert(o +" found");
//second way
    var exists = eval(document.x["field1"]);
    if(exists) 
	alert("true");
//second way is more efficient
//the first way is sequential
//second is random access
}
</script>
<body onload=e();>
<form name=x>
<input type=text name=field1>
</form>
</html>