Sunday, May 1, 2011

Jquery Function for skipping to a textbox on keypress

Hi all,

I currently have 4 textboxes which will be used to store an ip address. What i need help with is a function that will allow a user to input a "." and have the textbox change focus from the current textbox to the next textbox.

Thanks in advance

From stackoverflow
  • textbox.onChange = function(){
       if(textbox.value[textbox.value.length-1] =='.'){
         textbox.value = textbox.value.substring(0,textbox.value.length-2);
         nextTextbox.focus();
       }
    }
    

    I didn't test this but I think something in this general idea.

  • Can't you catch the onKeyPress event on the box and if the char is matches a "." focus on the next box? For example:

    var dotCode = ".".charCodeAt( 0 );
    $("box0").bind( "keypress", function( e ){ 
        if( e.keyCode === dotCode ){ $("box1").focus( ); }
    });
    
    // etc...
    
  • Assuming your textboxes are named ip0, ip1, ip2, ip3:

    $(document).ready( function() {
     $('#ip0,#ip1,#ip2').keydown( function(event) {
        var key = event.charCode || event.keyCode || 0;
        if (key == 190) {
            event.preventDefault();
         var i = Number(this.id.replace(/ip/,'')) +1;
         $('#ip'+i).focus();
        }
     });
    });
    
    AlteredConcept : Thanks tvanfosson! This is exactly what i was looking for.
  • I would rather use a "mask"-plugin, like this one: http://digitalbush.com/projects/masked-input-plugin/
    That would give you the opportunity to give it a nice look and still let your visitors copy an IP and pasting it.

    Will Dean : +1 from me - I have never worked out who's supposed to be helped by most of the overcomplicated methods of entering IP addresess.
    AlteredConcept : i don't know if that will work with an ip address though, since each octet can vary from 1 to 3 integers.

0 comments:

Post a Comment