skip to Main Content

What I’m trying to achieve is that when tab key is pressed, the cursor will be focused on the next empty input in a grid component. Input field that has value will be skipped. If the cursor currently is in input field 2, and input field 3 has value, when tab is pressed, the cursor will jump to input field 4. This is to speed up the form entry time.

Below is the html grid component that I have created

<div class="col-md-6" id="dcNonRetainValue">
<fieldset class="ES-border frame-height-collapsed">
    <legend class="ES-border">{{ 'Data Collection' }} </legend>
    <collect-paged-data data="ui.dataCollectionItems" currentPage="ui.dataCollectionItemsCurrentPage" pageSize="ui.dataCollectionPageSize">
    </collect-paged-data>
</fieldset>

Trying to focus next input element with js.

setTimeout(function () {
   $('#dcNonRetainValue *:input:empty').focus();
}, 50);

It does not seem to work correctly. Any feedback is appreciated.

2

Answers


  1. Using id will only give you the first element with that id. Use class instead.

    Login or Signup to reply.
  2. You can use filter function to select all the empty inputs. Then use eq function to select first input and use focus function. You can do like below Example:

    $(document).ready(function() {
    
      $('input').on( 'keydown', function( e ) {
        if( e.keyCode == 9 ) {
        
          const allEmptyInput = $('input').filter(function() {
            return $(this).val() === ""; 
          });
          
          // Return if there is no Empty Input      
          if (allEmptyInput.length === 0) return;
        
          e.preventDefault();
    
          const currentInput = $(e.target);
    
          const nextAllEmptyInput = currentInput.nextAll('input').filter(function() {
            return $(this).val() === ""; 
          });
          
          // Focus on first input if last is focus
          if (nextAllEmptyInput.length === 0) {
            allEmptyInput.eq(0).focus();
            return;
          }
    
          const firstEmptyInput = nextAllEmptyInput.eq(0);
          firstEmptyInput.focus();
    
         }
      });
      
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
    
    <label>First Input</label><br/>
    <input type="text"/>
    <br/>
    <label>Second Input</label><br/>
    <input type="text"/>
    <br/>
    <label>Third Input</label><br/>
    <input type="text"/>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search