I have two input elements and a button as follows:
<input class="close-acc-usr opt-in" type="text" name="closeAccUsr" />
<input class="close-acc-pin opt-in" type="number" name="closeAccPin" />
<button class="opt-btn close-btn">→</button>
In js I want to by clicking on the button, both input element contents become clear, so I write this line of code in the button event handler function:
document.querySelector('.opt-in').value = '';
but it does not work!! in fact if I write above code for '.close-acc-pin' and '.close-acc-usr' class names instead of .opt-in it works! but why with '.opt-in' it does not work?
Try to select all inputs with querySelectorAll :
const btn = document.querySelector('.opt-btn')
btn.addEventListener('click', function() {
const inputs = document.querySelectorAll('.opt-in');
inputs.forEach(input => input.value = '')
})
<input class="close-acc-usr opt-in" type="text" name="closeAccUsr" />
<input class="close-acc-pin opt-in" type="number" name="closeAccPin" />
<button class="opt-btn close-btn">→</button>
Instead of using two classes for that input why not change that opt-in class into an id like this:
<input id="opt-in" class="close-acc-usr" type="text" name="closeAccUsr" />
→
Then in your JS this:
document.querySelector('#opt-in').value = '';
or better still this
document.getElementById('opt-in').value = '';