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?
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
.innerHTMLproperty. I’d guess that the specific error relates to your browser’s internal mechanism for representing that list in its ownWrappedNativetype.Iterate the results instead; in your case, you only need the first result, so get it with the array accessor syntax
[0].But, since
nameproperties relate to form components, you should useidinstead. Retrieving an element by ID is easier, since IDs are [supposed to be] unique.Also, since Javascript has no references, you cannot store
innerHTMLin a variable and change it expecting the original property to change; you must make the assignment in the same statement in which you notateinnerHTML: