开发者

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

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();


I created a plugin for a similar question earlier today. Check it out!

This doesn't do any validation, but perhaps you can change it yourself.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜