verlager
verlager

Reputation: 876

js tab to next input field

I have a 1-character input field which should autotab to next input when filled to maxlength (or "keyup") but what happens is the cursor just moves to the right (ouside of the input) and the function someFunc() shows the alert but the cursor doesn't tab to next input of ".input".

function someFunc() {alert ("Hi!"); $(this).next('.inputs').focus();}
<input type="text" tabindex = i id="R${i}" onkeyup="someFunc();" maxlength = "1" size = "1" class = "inputs" />

Upvotes: 0

Views: 699

Answers (2)

verlager
verlager

Reputation: 876

Thank you all for your help. This old-school way was the only code that worked.

function someFunc(real_id) {
dog = real_id;
cat = dog.substring(1,5); cat++; cat++;
temp = "R" + cat; 
document.getElementById(temp).focus();
}

<input type="text" tabindex = i id="R${i}" onkeyup="someFunc(this.id);" maxlength = "1" size = "1" class = "inputs" />

Upvotes: 0

Crystal
Crystal

Reputation: 1992

Heres another way you can do it.

$(document).ready(function(){
    $('input').keyup(function(){
        if($(this).val().length==$(this).attr("maxlength")){
            var i = $('input').index(this);
            $('input').eq(i+1).focus();
        }
    });
});
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
<input type="text" maxlength = "1" size = "1"  class = "inputs"  />
<input type="text" maxlength = "4" size = "4"  class = "inputs"  />
<input type="text" maxlength = "4" size = "4"  class = "inputs"  />

I'm not sure what's going on with your code. But here's a working sample for you that might help you.

var elts = document.getElementsByClassName('inputs')
Array.from(elts).forEach(function(elt){
  elt.addEventListener("keyup", function(event) {
    
    if (event.keyCode === 13 || elt.value.length == 1) {

      elt.nextElementSibling.focus()
    }
  });
})
<input type="text" class="inputs" size ="1" id="0" maxlength="1"/>
<input type="text" class="inputs" size ="6" id="1" maxlength="5"/>

Upvotes: 1

Related Questions