0
let a = document.querySelector('#b1').value;
console.log(`a: ${a}`);
document.querySelector('#b1').value = 10;
console.log(`a: ${a}`);
DecPK
  • 24,537
  • 6
  • 26
  • 42
  • 5
    `a` is a copy of the value, it's not linked to the input permanently. You need to assign the variable again. – Barmar Oct 12 '21 at 06:20
  • `let a = document.querySelector('#b1')` and `console.log(\`a: ${a.value}\`)` will give you the correct ressult – Hao Wu Oct 12 '21 at 06:25
  • It will work if you store the element with id b into the variable a, and then fetch it's value whenever required, in that way you will always be able to access the updated value of element with Id b . – Diksha Goyal Oct 12 '21 at 06:27
  • Related: [Array value not updated after changing variable value](/q/43682194/4642212), [Why is the value of my input always empty if I store it in a variable?](/q/58078160/4642212), [Is JavaScript a pass-by-reference or pass-by-value language?](/q/518000/4642212). – Sebastian Simon Oct 12 '21 at 06:31

1 Answers1

1

As said in the comments,

When you do let a = document.querySelector('#b1').value; it will parse the value and save it in the variable a.

So doing so, it won't be updated. To get the actual value, you'll need to get it every time.

Like so :

let wrongWay = document.getElementById("foo").value; // Getting it the wrong way
let rightWay = document.getElementById("foo"); // Getting it the right way
console.log("wrong way value : " + wrongWay);
console.log("right way value : " + rightWay.value);

// Changing input value
document.getElementById("foo").value = "new value";
console.log("Changed value !");

console.log("wrong way value : " + wrongWay); // The value isn't updated as it is saved as a string -> so it didn't get any update
console.log("right way value : " + rightWay.value); // By getting it, you are sure to get the right value
<input id="foo" type="text" value="old value" >
polypode
  • 501
  • 3
  • 14