Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript > If I set "var x = document.getElementById('inputText').value" and I update "x", why doesn't the value update?

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>
like image 790
sapiensgladio Avatar asked Jan 19 '23 13:01

sapiensgladio


2 Answers

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.

like image 99
Jared Farrish Avatar answered Jan 25 '23 22:01

Jared Farrish


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";
like image 41
Guffa Avatar answered Jan 25 '23 22:01

Guffa