Ti J
Ti J

Reputation: 271

How to Set & Focus the last input text once user finishes typing from the 1st input text

I have multiple input text inside a table. How can I automatically set value & focus the last input text once I'm done typing values from the 1st input text box?

<td> <input type="text"/> </td>
<td> <input type="text"/> </td>
<td> <input type="text"/> </td>
<td> <input type="text"/> </td>
<td> <input type="text"/> </td>
<td> <input type="text"/> </td>
<td> <input type="text"/> </td>
<td> <input type="text"/> </td>
<td> <input type="text"/> </td>
<td> <input type="text"/> </td>
<td> <input type="text"/> </td>
<td> <input type="text"/> </td>

my js code:

var d =  id('my_table', document); 
for (var x=1; x<d.rows.length; x++) {                    
    d.rows[x].cells[12].firstChild.innerText = x;                   
    d.rows[x].cells[12].firstChild.focus();     
}

Upvotes: 0

Views: 1052

Answers (2)

hansmaad
hansmaad

Reputation: 18905

You could handle the blur event or the keypress event (to handle that the user pressed Enter) or a combination of both:

var inputs = document.querySelectorAll('#table input');
inputs[0].addEventListener('blur', setFocus);
inputs[0].addEventListener('keypress', function(e) {
   if (e.keyCode === 13)
     setFocus();
});

function setFocus() {
  inputs[inputs.length - 1].value = '123';
  inputs[inputs.length - 1].focus();
}
<table id="table">
   <tr><td><input type="text" ></td></tr>  
   <tr><td><input type="text" ></td></tr>  
   <tr><td><input type="text" ></td></tr>  
</table>

Upvotes: 1

Niklesh Raut
Niklesh Raut

Reputation: 34914

I am not sure, It the same as your want but its helps you, try this

<script src="http://code.jquery.com/jquery.min.js"></script>
<td> <input type="text" maxlength="4" tabindex="1" /> </td>
<td> <input type="text" maxlength="4" tabindex="3" /> </td>
<td> <input type="text" maxlength="4" tabindex="4"/> </td>
<td> <input type="text" maxlength="4" tabindex="2" /> </td>
<script type="text/javascript">
jQuery("input").on('input',function () {
    if(jQuery(this).val().length == jQuery(this).attr('maxlength')) {
        nextinput = parseInt(jQuery(this).attr('tabindex'))+1;
        // Here you can take current input value and set where you want
        jQuery("input[tabindex="+nextinput+"]").focus();
    }
});
</script>

Upvotes: 0

Related Questions