views:

569

answers:

2

I'm using mootools to toggle the display (and existence) of two DOM elements in one of my forms. Then, I am using javascript to validate the form to make sure that all of the required fields were filled in. The problem is that the the browser seems to be caching the elements. For example, I have html like this:

<input name="inputbox" id="inputbox" type="text" />
<select name="selection" id="selection">...</select>

And the javascript for validation is something like this:

if (form.inputbox != null && form.inputbox.value == "") {
  //don't submit form
{
else if (form.selection != null && form.selection.value == 0) {
  //don't submit form
}

Now, this works fine when the page is first loaded and the input element has been removed. However, when I click the button that replaces the input element with the select element, from then on the form.inputbox and form.selection in the javascript code contain the respective element as it was in its last state in the DOM - even if it is no longer in the DOM. So is the javascript caching the DOM and not updating the elements when they are removed from the DOM? What is going on here, and, more importantly, how should I go about fixing it?

Edit: I am using mootools to do the removing and replacing of the elements, the documentation for the respective functions can be found here and here.

A: 

Well, I can answer the second part of my question now: how to fix it. If you are using mootools, then use the dollar function (or getElementById might work) instead of using form.selection and form.inputbox:

if ($("inputbox") != null && $("inputbox").value == "") {
  //don't submit form
{
else if ($("selection") != null && $("selection").value == 0) {
  //don't submit form
}

It works, but I don't have an explanation for why the other didn't...

Steven Oxley
+1  A: 

Evaluating an element by name (form.elementName) when non-existent returns undefined. Evaluating the property value of an object ($('elementId')) returns null. Undefined and null are treated differently.

Zurahn
that's the answer I was looking for :P
Steven Oxley
this was the question I looking for :P
Zurahn