0

I have the following code:

var things = document.querySelectorAll("input.thing_input");
things.forEach(thing => {
    console.log(thing.name);
    if (thing.value == 0) {
        thing.value = "3";
    }
}

It was supposed to change the input field as if it was an actual input change, but it only changes it visually (it does not change in the HTML and cannot be saved properly because of that).

Dolphin
  • 27
  • 7
  • By the way, it does not have anything to do with the if statement. I debugged and it does in fact get through that. – Dolphin May 02 '23 at 12:28
  • Try `thing.setAttribute('value', '3')`. – Dogbert May 02 '23 at 12:29
  • The `value` reflected property doesn't reflect the `value` attribute, see [the linked question](https://stackoverflow.com/questions/43210254/javascript-program-works-well-in-ie-but-not-in-firefox-and-chrome-to-fill-in-i) for details. If you want to change the `value` *attribute*, either use `setAttribute` or assign to the `defaultValue` reflected property. – T.J. Crowder May 02 '23 at 12:37
  • @Dogbert It now shows up in the HTML, but it still doesn't work for some reason. Is there a way to simulate an actual user typing in the field? – Dolphin May 02 '23 at 12:37
  • You're missing a closing parantese `);` in the end. – ABR May 02 '23 at 12:39
  • It's shortened code... – Dolphin May 03 '23 at 00:07

1 Answers1

0

You can simulate an input event by triggering a built-in event.

const things = document.querySelectorAll('input.thing_input');

const initializeNumberValue = (numberInput, value) => {
  if (isNaN(numberInput.valueAsNumber)) {
    numberInput.value = value;
  }
};

const handleInputChange = ({ target }) => {
  initializeNumberValue(target, 3);
};

// Add listeners
things.forEach(input =>
  input.addEventListener('input', handleInputChange));

// Dispatch change for each...
things.forEach(thing => {
  console.log(thing.name);
  if (!thing.value) {
    thing.dispatchEvent(new InputEvent('input'));
  }
});
<form>
  <input type="number" class="thing_input" name="a" value="1" />
  <input type="number" class="thing_input" name="b" />
  <input type="number" class="thing_input" name="c" value="0" />
  <input type="number" class="thing_input" name="d" />
</form>
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132