Home > database >  tab key focus next empty input in a grid
tab key focus next empty input in a grid

Time:08-04

What I'm trying to achieve is that when tab key is pressed, the cursor will be focused on next empty input in a grid component. Below is the html grid component that I have created

<div  id="dcNonRetainValue">
<fieldset >
    <legend >{{ '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.

CodePudding user response:

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

CodePudding user response:

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 ) {
      e.preventDefault()

      const allEmptyInput = $('#my-form input').filter(function()      {
        return $(this).val() == ""; 
      });

      const firstEmptyInput = allEmptyInput.eq(0).focus();

      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"/>

  • Related