Grant Unwin
Grant Unwin

Reputation: 305

Jquery select NEXT text field on Enter Key Press

I have made a page using jquery, and on load it selects the first text field automatically. I want it to then move to the next field when the ENTER key is pressed.

$('.barcodeField input').bind('keyup', function(event) {
    if(event.keyCode==13){
       $("this + input").focus();     
    }
});

I can't find anything that works on the net. And I've scoured the forums.

Upvotes: 9

Views: 37263

Answers (7)

Farman Ameer
Farman Ameer

Reputation: 1462

This code works for me

HTML:

<div class="row">
<div class="col-md-3"> Name </div>
<div class="col-md-3"> <input type="text" /> </div>
</div>
<div class="row">
<div class="col-md-3"> Email</div>
<div class="col-md-3"> <input type="email" /> </div>
</div>

Jquery code:

 $(document).on('keypress', 'input,select', function (e) {
    if (e.which == 13) {
      e.preventDefault();
      $(this).parent().parent().next('div').find('input').focus();
    }
  });

Upvotes: 0

Hrushi
Hrushi

Reputation: 309

<!DOCTYPE html>

<html>
    <head>
        <title>TODO supply a title</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

    </head>
    <body>
        <input id="122" class='TabOnEnter' tabindex="1" /><br>
        <input id="123" class='TabOnEnter' tabindex="2" /><br>

         <input type="text" name="abc" /><br>
          <input type="text" name="abc1" /><br>
           <input type="text" name="abc2" /><br>
           <input type="text" name="abc3" class='TabOnEnter' tabindex="3" /><br>

        <input  class='TabOnEnter' tabindex="4" /><br>
        <input  class='TabOnEnter' tabindex="5" /><br>
        <input  class='TabOnEnter' tabindex="6" /><br>
<!--        <textarea class='TabOnEnter' tabindex="6">Hi, I am a test area</textarea>-->
        <input type="submit" value="submit" class='TabOnEnter' tabindex="7">


         <script src="//code.jquery.com/jquery-2.1.1.min.js"></script>
        <script>
            $(document).on("keypress", ".TabOnEnter", function (e)
            {
                //Only do something when the user presses enter
                if (e.keyCode == 13)
                {
                    var nextElement = $('[tabindex="' + (this.tabIndex + 1) + '"]');
                    console.log(this, nextElement);
                    if (nextElement.length)
                        nextElement.focus()
                    else
                        $('[tabindex="1"]').focus();
                }
            });

//Hidden inputs should get their tabindex fixed, not in scope ;)
//$(function(){ $('input[tabindex="4"]').fadeOut();  })
        </script>
    </body>
</html>

Upvotes: 0

Alan B. Dee
Alan B. Dee

Reputation: 5616

Here is the solution I came up with. The issue I had was that I needed to maintain tabindex, i.e. it had to function exactly that same as hitting tab. It uses both underscore and jquery.

I've left in my debugging code:

try {
    var inputs = $("input[id^=tpVal-]");
    var sortedInputs = _.sortBy(inputs, function(element){
        var tabIndex = $(element).attr('tabindex');//debugging
        var id = $(element).attr('id');//debugging
        console.log(id +" | "+ tabIndex +" | "+ $(element));//debugging
        return parseInt($(element).attr('tabindex'));
    });
    $(sortedInputs).each(function (index, element) {
        $(element).keyup(function(event){
            if(event.keyCode==13) {
                var $thisElement = $(element);//debugging
                var nextIndex = index+1;//debugging
                var $nextElement = $(sortedInputs[nextIndex]);
                var thisId = $thisElement.attr('id');//debugging
                var nextId = $nextElement.attr('id');//debugging
                console.log("Advance from "+thisId+" to "+nextId);//debugging
                if($nextElement!=undefined) {
                    $(sortedInputs[index + 1]).focus();
                }
            }
        });
    });
} catch (e) {
    console.log(e);
}

Upvotes: 0

penacho123
penacho123

Reputation: 21

try this:

(function($){
    $.fn.enterNext = function(){
       var _i =0;
       $('input[type=text], select',this)
            .each(function(index){
            _i = index;
            $(this)
                .addClass('tab'+index)
                .keydown(function(event){
                    if(event.keyCode==13){
                        $('.tab'+(index+1)).focus();
                        event.preventDefault();
                    }
                });

        })
     $( "input[type=submit]",this ).addClass('tab'+(_i+1));
}})(jQuery);

for use:

$('form.element').enterNext();

in my case this is the best solution in that I got because the function .next() is strict with elements outside their branch DOM. The best way is to force an index.

and sorry for my bad English...

Upvotes: 2

Martin Parry
Martin Parry

Reputation: 319

I've created a little function which can do what you need. This is the version I use so you may need to change the class names but you should get the idea.

<script type="text/javascript">
$(document).ready(function(){
$(".vertical").keypress(function(event) {
        if(event.keyCode == 13) { 
        textboxes = $("input.vertical");
        debugger;
        currentBoxNumber = textboxes.index(this);
        if (textboxes[currentBoxNumber + 1] != null) {
            nextBox = textboxes[currentBoxNumber + 1]
            nextBox.focus();
            nextBox.select();
            event.preventDefault();
            return false 
            }
        }
    });
})
</script>

So basically:-

  • Get all the input fields matching .vertical
  • Find which is the current text box
  • Find the next one
  • Set the focus on that one

Upvotes: 17

Charlie Martin
Charlie Martin

Reputation: 112366

Basically, you just need top have the DOM elements in some structure so that you can select the next one. I'd suggest exploiting tabindex, but anything that let's you have a defined order will work.

Upvotes: 0

Sarfraz
Sarfraz

Reputation: 382696

You should use:

$(this).next('input').focus();  

Upvotes: 11

Related Questions