Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

clearing input fields upon pressing enter

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 = "";

    }
},
like image 836
meteorBuzz Avatar asked Oct 24 '25 03:10

meteorBuzz


2 Answers

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" />
like image 142
Tomas Hromnik Avatar answered Oct 26 '25 18:10

Tomas Hromnik


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:


  1. It is not good idea to use same id for multiple elements, id must be unique.

  2. Use Jquery libary if you are including it $("#id") much simpler and neat than document.getElementById("id")

like image 36
dsharew Avatar answered Oct 26 '25 16:10

dsharew