Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Find out whether a node exists 2

Status
Not open for further replies.

kaeserea

Programmer
Feb 26, 2003
164
0
0
DE
Hello!

I usually get the values of form elements with the method getElementById("myId"). I have now a case where the form element maybe there or not. Thus I first need to find that out as to not receive an error like "element is null or not an object".

Does anybody know if there's a function like exists() isNode() or something like that?

Best regards
Eva
 
Couldn't you check the value of the node by putting it into a variable, and then testing whether it's null or not?
 
Hi kaeserea, using a try/catch clause will accomplish what you're looking to do. What I would suggest is saving the values from the form elements into variables, and if the form elements don't exist set the values to null instead. Try out this sample I typed up to help give you an idea of how to incorporate it into your application:
Code:
<html>
<head>
<script language=javascript>

function displayValue(str) {
   try {
      obj = document.getElementById(str);
   }
   catch(e) {
      obj = null;
   }
   if (obj == null) {
      alert("textbox does not exist");
   }
   else {
      alert("textbox value is:\n\n" + obj.value);
   }
}

</script>
</head>
<body>
<form name=blahForm>
<input type=text id=text1>Textbox1<br>
<input type=button value='display textbox1 value' onclick='displayValue("text1")'><br><br>
No textbox2 exists!!<br>
<input type=button value='display textbox2 value' onclick='displayValue("text2")'><br><br>
</form>
</body>
</html>

-kaht

banghead.gif
 
getElementById should return null if it can't find the element. You should be able to do this:
Code:
obj = document.getElementById(str);
if(obj){
  alert('Object exists!');
}

Adam
"Computers make it easier to do a lot of things, but most of the things they make it easier to do don't need to be done." Andy Rooney.
 
Hello!

Thanx for all of your help. That's great to get three good answers. They work well.

Best wishes !
Eva
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top