Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I fire the Tab keypress when the Enter key is pressed?

Tags:

javascript

This is what I have and it works fine. But I want to return the tab key instead of just nothing happening.

$(document).on("keypress", ":input:not(textarea):not([type=submit])", function(event) {
    if (event.keyCode == 13) {
        event.preventDefault();
    }
});

What I want is:

if (event.keyCode == 13) {
    event.preventDefault();
    return event.keyCode = 9; <<= or something similar and simple
}

This seems like a duplicate but I don't see anything to substitute enter for tab code... Tab key already knows to skip hidden and use tab orders.

like image 671
Daniel Yantis Avatar asked Dec 05 '25 07:12

Daniel Yantis


1 Answers

I suspect what you really want is to move to the next field in the form.

If so, you can easily find the next form field and use .focus() to focus it. For instance:

var fields = $(this).closest("form").find("input, textarea");
var index = fields.index(this) + 1;
fields.eq(
  fields.length <= index
  ? 0
  : index
).focus();

Example:

$(document).on("keypress", ":input:not(textarea):not([type=submit])", function(event) {
  if (event.keyCode == 13) {
    event.preventDefault();
    var fields = $(this).closest("form").find("input, textarea");
    var index = fields.index(this) + 1;
    fields.eq(
      fields.length <= index
      ? 0
      : index
    ).focus();
  }
});
<form>
  <div>
    <label>
      Field 1:
      <input type="text">
    </label>
  </div>
  <div>
    <label>
      Field 2:
      <input type="text">
    </label>
  </div>
  <div>
    <label>
      Field 3:
      <input type="text">
    </label>
  </div>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

If you're using tabindex to put fields in a different order than document order, you'll have to do a bit more work, basically sorting the result of find on tabindex and working from there. But that should get you going the right way.

like image 73
T.J. Crowder Avatar answered Dec 07 '25 20:12

T.J. Crowder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!