clearing input fields upon pressing enter
Solution 1
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 2
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 thandocument.getElementById("id")
Comments
-
meteorBuzz almost 2 years
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 = ""; } },
-
dsharew almost 9 yearsThanks dude I updated my answer. You know I dont remember the time I was using same id for many inputs ( It is not good practice is the message) lol.