Why does this javascript throw this particular error?

In my HTML code, I have a button that, when clicked, launches a javascript function. This is the HTML code for the button:

<button type="button" onclick="repeatName()">Click me!</button> 

I want the user to enter something into the text box (which is inside the form). This is the code for the text field:

 <input type="text" name="txtName" /> 

I want this innerHTML div to change according to the information placed in the name text box after the button is clicked. This is the code for the div:

 <div name="editThis" width="50px" height="50px" border="1px"> </div> 

When the button is pressed, I want it to launch the function below. It is supposed to change innerHTML div.

 function repeatName() { var editField = document.getElementsByName("editThis").innerHTML; var repeatedName = document.theForm.txtName.value; editField = (repeatedName + " is the value.") } 

PROBLEM: every time a button is clicked, I see this error in the Firefox error console:

 Error: uncaught exception: [Exception... "Cannot modify properties of a WrappedNative" nsresult: "0x80570034 (NS_ERROR_XPC_CANT_MODIFY_PROP_ON_WN)" location: "JS frame :: chrome://global/content/bindings/autocomplete.xml :: onxblpopuphiding :: line 825" data: no] 

What is this error and how to fix it?

+4
source share
3 answers

According to the documentation , document.getElementsByName(str) returns a "list of elements".

Clearly, the "list of elements" does not have a single .innerHTML property. I assume that the specific error relates to your internal browser engine for representing this list in its own WrappedNative type.

Iterate over the results; in your case, you only need the first result, so get it with the syntax of accessing the array [0] .

But, since the name properties apply to the components of the form, id should be used instead. Retrieving an item by ID is easier because identifiers [must be unique].

Also, since Javascript has no references, you cannot save innerHTML in a variable and change it, waiting for the original property to change; you must make the assignment in the same statement in which you mark innerHTML :

 function repeatName() { var editField = document.getElementsById("editField"); var repeatedName = document.theForm.txtName.value; editField.innerHTML = repeatedName + " is the value." } 
+11
source

I think that Tomalak is right. Alternatively, you can give your div an id, and then use getElementById, which will return a single object, not a collection.

i.e.

 <div id="editThis" .... > .... </div> ... ... document.getElementById("editThis").innerHTML = repeatedName + " is the value"; 
+1
source

Div elements do not have a name attribute, so use an identifier instead.

 <div id="editThis" ...> 

Then use:

 function repeatName() { var editField = document.getElementById("editThis"); if (editField) { editField.innerHTML = document.theForm.txtName.value + ' is the value'; } } 
0
source

All Articles