3zzy 3zzy - 4 years ago 107
Javascript Question

Finding the first empty input

<div class="input-group">
<input type="password" maxlength="1" value="" readonly="">
<input type="password" maxlength="1" value="" readonly="">
<input type="password" maxlength="1" value="" readonly="">
<input type="password" maxlength="1" value="" readonly="">
</div>


I have only these inputs on a page and I'm trying to focus and enter a value dynamically into each empty input:

document.querySelector('input[value=""]').value = 1


... works but only for the first input, shouldn't this select the next empty input everytime?

Answer Source

This works:

document.getElementById('fill').addEventListener('click', evt => {
  document.querySelector('input[value=""]').setAttribute('value', '1');
});
<div class="input-group">
    <input type="password" maxlength="1" value="" readonly="">
    <input type="password" maxlength="1" value="" readonly="">
    <input type="password" maxlength="1" value="" readonly="">
    <input type="password" maxlength="1" value="" readonly="">
</div>
<button id="fill">Fill</button>

.value = ... is not actually changing the attribute itself in the DOM. Use .setAttribute to make the actual change in the DOM that querySelector can see.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download