Simulating the TAB keydown: focusing next element as determined by `tabIndex`

后端 未结 5 1114
别那么骄傲
别那么骄傲 2020-12-15 18:38

I have two input elements, the first is focused, and I want to focus the second by simulating the TAB keypress/keydown event. (Note: I don\'t want to use .nex

5条回答
  •  一个人的身影
    2020-12-15 18:58

    Here is a solution using jquery to simulate the TAB functionallity with the Enter key:

    https://jsfiddle.net/tuho879j/

    $('input').keypress(function(event){
      if(event.which == '13')   //ENTER     
      {
        var tabIndex = $(this).attr('tabIndex');
    
        var all_inputs = $(this).closest('table').find('input:visible');
        var inputs = all_inputs.filter(function() {
          return $(this).attr("tabIndex") > tabIndex;
        })
    
        if(inputs.length != 0)
        {
            inputs = $(inputs).sort(function(a,b){
              return $(a).attr('tabIndex')-$(b).attr('tabIndex');
            });
        }
        else
        {
            inputs = $(all_inputs).sort(function(a,b){
              return $(a).attr('tabIndex')-$(b).attr('tabIndex');
            });
        }
    
    
        var elem = inputs.eq( inputs.index(this)+ 1 );
        if(elem.length == 0)
            elem = inputs.eq(0);
    
        elem.focus();
        event.preventDefault();
      }
    });
    

提交回复
热议问题