sad electron
sad electron

Reputation: 97

jquery select next button on enter in input text area

i have a lot of input text areas followed by a button, what i would like to do is to automatically make for every input box select the next button element after hitting enter without defining id or class for the input box or the button.

I think my problem lies in not being able to correctly use the next feature, i am kind of new to this:

    <input type="text"/> <button>enter</button> /after hitting enter in this input, it would click the button element /

    <input type="text"/> <button>enter</button> /after hitting enter in this input, it would hit enter in this button element/

     <script>
     $("input[type=text]").keyup(function(event){
    if(event.keyCode ==13){
    $("input[type=text]").next("input[type=text] button").click();
     }
     });

The above script part doesn't work, but if i give them ids or classes, then it works, for example, if i give the id "in" for input text, and "btn" for button, then it works for one input and button here:

 $("#in").keyup(function(event){
 if(event.keyCode ==13){
  $("#btn").click();
  }
  });

But i have way too many input boxes followed by buttons, i need to somehow make it so that each input box, after hitting enter selects the next button.

Please help

Upvotes: 2

Views: 779

Answers (2)

Ram
Ram

Reputation: 144689

Change:

$("input[type=text]").next("input[type=text] button").click();

to:

$(this).next("button").click();

Note that keyCode is not cross-browser, you can use which property instead.

$("input[type=text]").keyup(function(event){
    if ( event.which === 13 ) {
        $(this).next("button").click();
    }
});

Upvotes: 2

Jason Whitted
Jason Whitted

Reputation: 4024

I think this will do the trick for you.

$("input").keyup(function(event){
    if(event.which == 13) {
        $(this).next("button").click();
    }
});

Upvotes: 2

Related Questions