In the following example, why doesn’t the value
property of the input with the ID test
update to "second"
?
document.getElementById("test").addEventListener("click", () => {
let test = document.getElementById("test").value;
test = "second";
console.log(test); // Logs "second", but input value is not updated.
});
<label>Click on this test input: <input type="text" id="test" value="first"></label>
Because Javascript assigned x as a value and not a reference to the original object.
For example, you could instead:
function setText(x) {
document.getElementById('test').value = x;
}
getText = function() {
return document.getElementById('test').value;
}
And the value you set with setText()
will be reflected by getText()
, since getText()
will also use the reference object's value, and not a copy of the value.
EDIT
As Bryan points out, this would be a copy by reference with a global scope:
var test = document.getElementById('test');
function setText(x) {
test.value = x;
}
getText = function() {
return test.value;
}
http://jsfiddle.net/nLj2A/
The original test
variable stores a reference to the element, not a value associated with an attribute of the element.
You are copying the value to a variable. Changing the variable won't change the original, because the variable just contains a copy.
If you store the reference of the element in the variable, you can use that to set the value:
var test = document.getElementById('test');
test.value = "second";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With