wanted to extend jQuery to handle a custom enter key event based on tabindex

Posted by ullasvk on Stack Overflow See other posts from Stack Overflow or by ullasvk
Published on 2011-01-08T16:50:30Z Indexed on 2011/01/08 16:53 UTC
Read the original article Hit count: 227

Filed under:
|
|
|

I write the following code to handle when the enter key pressed an with few validation like if it is a textarea allow only four lines and if the value is empty, focus on itself.

var temp = 1;
 function getLines(id)
    {
      return temp=temp+id;
    }
$("#theform").keypress(function(e){
var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;                                
    if (key == 13) {
        var $targ = $(e.target);
        var tindex = $targ.attr("tabindex");
        var count =1;
        var focusNext = false;
        var allowedNumberOfLines = 4;
       if ($targ.is("textarea") && !$targ.is(":button,:submit")) {
          var lines= getLines(count);
            if (lines > allowedNumberOfLines)
            {
            $("#login_error").css('background', '#F7F77C').fadeIn(1000).html("Only "+allowedNumberOfLines+" Lines Allowed").fadeOut(1000);
            tindex++;
            $("[tabindex=" + tindex + "]").focus();    
            return false;
            }
        }
        else if($targ.val() =='' || $targ.val() == "undefined")
        {
        $("[tabindex=" + tindex + "]").focus();    
         return false;
        }
        else if($targ.val() !='' || $targ.val() != "undefined")
        {
        tindex++;
        $("[tabindex=" + tindex + "]").focus();    
         return false;
        }
    }
});

Is there any way to make it a custom function so that i can just call the function like

$('theform').returnPress();

© Stack Overflow or respective owner

Related posts about jQuery

Related posts about key