Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this javascript throw this particular error?

In my HTML code I have a button that when pressed runs 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 a text field (which is inside of a form). This is the code for the text field:

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

I want this div's innerHTML to be changed according to the information put in the name textbox once the button is pressed. This is the code for the div:

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

</div>

When the button is clicked, I want it to run the function below. It is supposed to change the innerHTML of the div.

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

    editField = (repeatedName + " is the value.")

}

THE PROBLEM IS that whenever the 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 can I correct it?

like image 509
idungotnosn Avatar asked Dec 16 '22 12:12

idungotnosn


2 Answers

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

It's clear that "a list of elements" doesn't have a singular .innerHTML property. I'd guess that the specific error relates to your browser's internal mechanism for representing that list in its own WrappedNative type.

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

But, since name properties relate to form components, you should use id instead. Retrieving an element by ID is easier, since IDs are [supposed to be] unique.

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

function repeatName() {
    var editField = document.getElementsById("editField");
    var repeatedName = document.theForm.txtName.value;

    editField.innerHTML = repeatedName + " is the value."
}
like image 151
Lightness Races in Orbit Avatar answered Jan 06 '23 04:01

Lightness Races in Orbit


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

i.e.

<div id="editThis" .... > .... </div>
...
...
document.getElementById("editThis").innerHTML = repeatedName + " is the value";
like image 25
Ord Avatar answered Jan 06 '23 02:01

Ord