After an a user presses enter inside an input field, I clear the value by document.getElementById('text').value = "";
As Im using a spacebars to iterate over an array, this displays multiple input fields with the same id of course id='text'
After typing in the first input field and pressing return key, the input field clear.
However, this is not the case for the proceeding inout fields. I understand document.getElementById only finds the first id.
How can I make this the input value is cleared for all input fields.
'keydown #text': function(event, template) {
if ((27 === event.which) || (13 === event.which)) {
event.preventDefault();
document.getElementById('text').value = "";
}
},
Never ever use ID for multiple elements. ID is unique and it can only be present once in the HTML document. Use class instead or regular HTML element selector:
'keydown input[type="text"]': function(event, template) {
if ((27 === event.which) || (13 === event.which)) {
event.preventDefault();
//this should delete value from the input
event.currentTarget.value = "";
}
}
And in HTML:
<input type="text" />
<input type="text" />
Solution:
You can iterate over all the matches and clear their value.
$("[id='text']").each(function(){
$(this).val("");
});
working example on jsfiddle, initially commented by @abdullah
Recommendations:
It is not good idea to use same id for multiple elements, id must be unique.
Use Jquery libary if you are including it $("#id") much simpler and neat than document.getElementById("id")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With