Andrus
Andrus

Reputation: 27975

Activating next input field in form on enter

Order entry form contains product code and quantity columns in multiple rows and delete button (-) in end of every row. It contains also add button in first column and after form.

Pressing enter key should set focus to next text or numeric input field (product code or quantity), skipping buttons.

I tried code below is used but enter key is ignored.

Chrome debugger shows that line $(this).next('input').focus() is executed but focus() call does not have any effect.

jquery, jquery-mobile, ASP.NET MVC4 are used

<!DOCTYPE html>
<html>
<head>
  <script src="/Scripts/jquery/jquery-1.9.1.js"></script>
</head>
<body>
  <div data-role="page" data-theme="a">
 <div data-role="content">
<script>
  $(function () {
    $('#inputform').on('keydown', 'input', function (event) {
      if (event.which == 13) {
        $(this).next('input').focus();
        event.preventDefault();
      }
    });
  });
</script>
<form id='inputform' method="post" 
   action ="/Detail/SaveFullDocument?_entity=DokG&amp;_id=0">
  <fieldset>
<div class='form-field' >
<label class='form-label' for='Tasudok'>Order number</label>
<input class='ui-widget-content ui-corner-all form-fullwidth'  id='Tasudok' name='Tasudok'  value=''  maxlength='25' /></div>

  <input type="hidden" name="_rows" />

  <table id="tableId">
    <tr>
      <th>Product code</th>
      <th>Quantity</th>
      <td>
        <input type="button" value="+" onclick="addRow('tableId')" /></td>
    </tr>

    <tr>
      <td>
        <input type="text" name="Toode" /></td>
      <td>
        <input type="number" name="Kogus" /></td>
      <td>
        <input type="button" value="-" onclick="deleteRow(this)" /></td>
    </tr>
  </table>

    <input type="button" value="+" onclick="addRow('tableId')" />
    <input type="submit" value='Save order' />
</form>

    </div>
  </div>
</body>
</html>

Upvotes: 11

Views: 54451

Answers (4)

Henry Ozoani
Henry Ozoani

Reputation: 133

Update Nov 2024:

This question and the accepted answer are old. Most of us aren't using JQuery anymore.

Here's a more modern answer using Vanilla JavaScript:

My solution would work:

  • on any kind of form
  • only for input fields
  • form is submitted (or any other default action happens) when Enter key is pressed on the last input field.

Create the function:


const moveToNextInputFieldOnEnter = (event: KeyboardEvent) => {
    if (event.code === "Enter") {
        const currentInput = event.target as HTMLInputElement;
        if (currentInput.nodeName != "INPUT") return;

        const form = currentInput.form;
        if (!form) return;

        const formInputs = Array.from(form).filter(
            (element) => element.nodeName === "INPUT"
        ) as HTMLInputElement[];

        const nextInputIndex = formInputs.indexOf(currentInput) + 1;
        if (nextInputIndex >= formInputs.length) return;

        const nextInput = formInputs[nextInputIndex];

        nextInput.focus();
        event.preventDefault();
    }
};

Then add event listener:


document.addEventListener("keydown", moveToNextInputFieldOnEnter);

If using React, add in a useEffect:


// move to next input field on enter key press
    useEffect(() => {
        document.addEventListener("keydown", moveToNextInputFieldOnEnter);

        return () => {
            document.removeEventListener(
                "keydown",
                moveToNextInputFieldOnEnter
            );
        };
    }, []);

Upvotes: 3

sir_dance_a_lot
sir_dance_a_lot

Reputation: 510

If you cannot or want to avoid to modify your inputs html, you can use the following snippet based on jQuery:

$('#inputform').on('keydown', 'input', function (event) {
    if (event.which == 13) {
        var $allInputs = $('#inputform input, #inputform select')
        var $this = $(event.target);
        var index = $allInputs.index($this);
        if (index < $allInputs.length - 1) {
            event.preventDefault();
            $allInputs[index+1].focus()
        }
    }
});

The if-case is implemented to not trigger the preventDefault() for the last input that is probably a submit.

Upvotes: 0

riyaolega
riyaolega

Reputation: 131

html bit

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">

</style>
</head>
<body>

<form id= 'form' >
      <input onkeydown='handleEnter(event)' placeholder="field 1" /><br>
      
      <input onkeydown='handleEnter(event)' placeholder="field 2" /><br>
      <input placeholder="field 3" />
    </form>

</body>
</html>

Jvascript bit

function handleEnter(event) {
   if (event.key==="Enter") {
      const form = document.getElementById('form')
      const index = [...form].indexOf(event.target);
      form.elements[index + 1].focus();
      //event.preventDefault();
    }
}

Upvotes: 4

Sam
Sam

Reputation: 2201

The problem is that the next input is sometimes a button. Here is a JS Fiddle with a possible solution:

http://jsfiddle.net/hxZSU/1/

I've added a data attribute to the html elements that are inputs for the user. The attribute also contains an incrementing index so that you can control the order of the elements receiving focus.

Here are the HTML changes:

<input class='ui-widget-content ui-corner-all form-fullwidth' data-index="1" id='Tasudok' name='Tasudok' value='' maxlength='25' />
<input type="text" name="Toode" class="my-input" data-index="2" />
<input type="number" name="Kogus" data-index="3" />

Here is the new JavaScript event that will move between the input fields. It will determine the index of the element is currently being edited by using $(event.target).attr('data-index'). It increments the index and selects the next element using this.

$('#inputform').on('keydown', 'input', function (event) {
    if (event.which == 13) {
        event.preventDefault();
        var $this = $(event.target);
        var index = parseFloat($this.attr('data-index'));
        $('[data-index="' + (index + 1).toString() + '"]').focus();
    }
});

Upvotes: 7

Related Questions