Clearing input fields when input is pressed
After the user clicks enter inside the input field, I clear the value document.getElementById('text').value = "";
As Im using spaces to iterate over an array, this displays multiple input fields with the same ID, of course id='text'
After entering in the first input field and pressing the return key, the input field is cleared.
However, this does not apply to outgoing inout fields. I understand that it document.getElementById
only finds the first id.
How can I do 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 = "";
}
},
source to share
Never use an ID for multiple items. The ID is unique and can only appear once in an HTML document. Use a class or a regular HTML element selector instead:
'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" />
source to share
Decision
You can iterate over all matches and clear them.
$("[id='text']").each(function(){
$(this).val("");
});
a working example on jsfiddle originally commented by @abdullah
Recommendations
-
It's a good idea to use the same identifier for multiple items, the identifier must be unique.
-
Use Jquery libary if you have included it
$("#id")
much easier and neat thandocument.getElementById("id")
source to share