Question

I am trying to make a system where when i fill a text box it moves onto the next. Currently I have this code:

 $('#txt1').keyup(function() {
    if(this.value.length == $(this).attr('maxlength')) {
       $('#txt2').focus();
    }
 });

I want to make this continues so it will go on to echo #txt3 #txt4 ect. Also would there be a way to change the focused text box via the arrow keys. E.G. when up arrow key is pressed selected is changed from #txt4 to #txt3 and the opposite for the down key.

Thanks in advance.

Was it helpful?

Solution

Here is the code to address your first question. I added a class attribute for convenience and replaced the "maxlength" attribute by the HTML "size" attribute.

HTML

<p><input type="text" class="navigable" id="txt1" data-number="1" size="2" placeholder="dd"></p>
<p><input type="text" class="navigable" id="txt2" data-number="2" size="2" placeholder="mm"></p>      
<p><input type="text" class="navigable" id="txt3" data-number="3" size="4" placeholder="yyyy"></p>     

JS

$('.navigable').keyup(function() {
var self = $(this);
var next = $('#txt'+(self.data('number')+1));
if(next.length > 0 && self.val().length == self.attr('size')) {
   next.focus();
}

});

You can try it here

I have my doubts concerning your request about the arrow keys binding. What happens if the user wants to navigate in one of the inputs? Nevertheless, here is the code to take into account the arrow keys:

HTML

<p><input type="text" class="navigable" id="txt1" data-number="1" size="2" placeholder="dd"></p>
<p><input type="text" class="navigable" id="txt2" data-number="2" size="2" placeholder="mm"></p>
<p><input type="text" class="navigable" id="txt3" data-number="3" size="4" placeholder="yyyy"></p>

JS

$('.navigable').keyup(function(e) {
  var self = $(this);
  var currentInput = self.data('number');
  var next = $('#txt'+ (currentInput + 1));
  var previous = $('#txt'+ (currentInput - 1));
  var keyCode = e.keyCode || e.which;
  if(next.length && keyCode === 40)
      next.focus();
  else if(previous.length && keyCode === 38)
      previous.focus();
  else if(next.length && self.val().length == self.attr('size')) {
     next.focus();
  }

});

You can try it here

OTHER TIPS

You can have a keypress event which checks for the key pressed and based on the key pressed take necessary action! EDIT: You can know which key was pressed by passing a parameter in your function call

.keypress(function(e))
{
    if(e.which == 13)
       //take necessary action for enter key
    etc
}

Bind a keydown event and check for the proper event.which:

  • Left: 37
  • Up: 38
  • Right: 39
  • Down: 40
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top