Tabindex based on enter key by getting form elemens not working in Jquery

前端 未结 2 537
自闭症患者
自闭症患者 2021-01-17 01:45

I have a form, and I am able to get all form elements through serializeArray(). I want to focus() on form elements based on their tabindex value us

相关标签:
2条回答
  • 2021-01-17 02:08

    You can also try this HTML

    <input id="122" class='TabOnEnter' tabindex="1" /><br>
    <input id="123" class='TabOnEnter' tabindex="2" /><br>
    <input id="124" class='TabOnEnter' tabindex="4" />This input is hidden<br>
    <input id="124" class='TabOnEnter' tabindex="5" /><br>
    <input id="125" class='TabOnEnter' tabindex="3" /><br>
    <textarea class='TabOnEnter' tabindex="6">Hi, I am a test area</textarea>
    

    SCRIPT ///////////

    $(document).on("keypress", ".TabOnEnter" , function(e)
      {
        //Only do something when the user presses enter
        if( e.keyCode ==  13 )
        {
           var nextElement = $('[tabindex="' + (this.tabIndex+1)  + '"]');
           console.log( this , nextElement ); 
           if(nextElement.length )
             nextElement.focus()
           else
             $('[tabindex="1"]').focus();  
        }   
      });
    
    //Hidden inputs should get their tabindex fixed, not in scope ;)
    //$(function(){ $('input[tabindex="4"]').fadeOut();  })
    

    ////////////// Worked Fine in EI,Chrome, Mozilla . not tested in safari and other browser

    0 讨论(0)
  • 2021-01-17 02:19

    I think I understand what you want to do. I rewrote your code and ended up with this:

    (function($){
    
        $.fn.entertab = function(options) {
    
            var defaults = {
                maxTabIndex: 20
            };
    
            options = $.extend({}, defaults, options);
    
            return this.filter('form').each(function(){
    
                var $this = $(this),
                    $elms = $this.find("[tabindex]");
    
                $elms.each(function(){
                    var $elm = $(this),
                        idx = parseInt($elm.attr("tabindex"));
                    if (idx > options.maxTabIndex) {
                        return;
                    }
                    $elm.keydown(function(e){
                        if (e.which == 13 && ($elm.val() != '')) {
                            $elms.filter("[tabindex="+(idx+1)+"]").focus();
                            e.preventDefault();
                        }
                    });
                });
            });
        };
    
    })(jQuery);
    

    There's a working example on jsFiddle.

    0 讨论(0)
提交回复
热议问题