0

So I have a simple form-extension script:

var counter=1;
function newField(counter) {
    counter++;
    var newFields = document.getElementById('readroot').cloneNode(true);
    newFields.id = "formcheck"+counter;
    newFields.style.display = 'block';
    var newField = newFields.childNodes;
    var insertHere = document.getElementById('writeroot');
    insertHere.parentNode.insertBefore(newFields,insertHere);
}

being called inside of a form:

<form id='newanimal' action='/submit' method='post'>    
<span id='writeroot'></span>
<button id='newField' type='button' onclick=newField();>Add Field</button>
</form>

readroot looks like this:

<div id="readroot" style="display: none">

<input type="button" value="Remove review"
            onclick="this.parentNode.parentNode.removeChild(this.parentNode); counter--;" /><br /><br />

<input id="checkform" name="checkform" value="New Checkform" />
</div>

Now the function works fine, unless it's called from inside of a form. When executed as-is, I get newField is not a function called as an error, however if you remove the form tags and it runs fine.

Any idea what's going on?

1
  • check by changing the id of your button 'newField' to some other Commented Jul 25, 2011 at 15:48

1 Answer 1

3
<button id='newField' type='button' onclick=newField();>Add Field</button>

When an element has an id property, the element is accessible using the global variable of that name. So your function newField is overwritten by a reference to the element with the id newField. Since it is now an HTML element, it is evidently "not a function".

WhatWG spec for this. Note that this is not behaviour you should rely upon, but you should be wary of it for exactly this reason. Note that unpredictable behaviour in the global scope is a very good reason to avoid using the global scope.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.