clearing input fields upon pressing enter

11,597

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:


  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")

Share:
11,597
meteorBuzz
Author by

meteorBuzz

Seeking ways to solve real world problems.

Updated on June 07, 2022

Comments

  • meteorBuzz
    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
    dsharew almost 9 years
    Thanks 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.