Correct way of setting hidden value fields in javascript

61 Views Asked by At

in javascript i am using this code to set the value of some hidden fields on a page that is not mine

let hiddenField = document.querySelectorAll('input[type="hidden"].class1');
for (k = 0; k < hiddenField.length; k++) {
        console.log("previous value: " + hiddenField[k].value);
        hiddenField[k].value = hiddenValue;
        console.log("new value: " + hiddenField[k].value);
        console.log(hiddenField[k]);
}

The problem is that only one of the two hidden values is being correctly setted, in fact the output I obtain on the console is

previous value: 0
new value: 4.5
<input type=​"hidden" name=​"left.result.0.stars" class=​"class1" value=​"4.5">​
previous value: 0
new value: 4.5
 <input type=​"hidden" name=​"right.result.0.stars" class=​"class1" value=​"0">​

as you can see when I print hiddenField[k].value the value is correctly setted but when I print the element on the console the value has been not setted, what can be the problem?

1

There are 1 best solutions below

6
Pluto On

You can set value of hidden input like this:

<body>
  <input type="hidden" name="left.result.0.stars" class="class1" value="0" />
  <input type="hidden" name="right.result.0.stars" class="class1" value="0" />
  <script>
    let hiddenField = document.querySelectorAll('input[type="hidden"].class1');
    let hiddenValue = 4.5;
    for (k = 0; k < hiddenField.length; k++) {
      console.log("previous value: " + hiddenField[k].value);
      hiddenField[k].value = hiddenValue;
      console.log("new value: " + hiddenField[k].value);
      console.log(hiddenField[k]);
    }
  </script>
</body>

This code works fine