Kevin Kevin - 1 month ago 4
HTML Question

Changing value of input text after button click using javascript's addeventlistener

I am trying to have the input text that was entered via a text field form change on button click using JavaScript. I'm having difficulty figuring out why it is not working. Any help would be appreciated.

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title> </title>

<script type="text/javascript">


function start(){
var button = document.getElementById("button");
button.addEventListener("click", buttonPressed, false);
}

function buttonPressed(){
var text = document.getElementById("textField").value;
text.value = "GMU";
}

window.addEventListener("load", start, false);

</script>

</head>

<body>
<form>
<input id="textField" type="text" value="">
<input id="button" type="button" value="Button">
</form>
</body>
</html>

Answer

The problem lies here:

var text = document.getElementById("textField").value;
text.value = "GMU";

Take a look at the lines above. You are getting the value of an element and storing it into text but you then try to assign text.value? Consider this situation:

Say that the input currently has a value of "Apples". Doing:

var text = document.getElementById("textField").value;

Will store "Apples" in text. Now you do:

text.value = "GMU";

Since text is a string, and you try to access property value which does not exist for strings, it doesn't work - you've access the value property one too many times.

Now - note that the variable stores the value not reference to the element's value, meaning that in your code above, text only holds the property value, it's not pointing to the actual element's value property. Thus you would need to directly modify the value property like so:

document.getElementById("textField").value = "GMU";

This works because you modify the property of the element itself, you don't copy it into a variable.


You can alternatively store the element into a variable, and do element.value = "val" because an element is an object, and objects have references that point to memory, so when you assign to an object, reference is assigned and it points to the same place in memory.

Comments