KPK KPK - 1 month ago 12
jQuery Question

jQuery trigger .click() when selected by keyboard

I have a table with form inputs, at the bottom of the table, I have an "Add row" button. My issue is I'm starting in an input box, and hitting tab to move to this

<a>
add row button. When I hit enter with the link selected it's not triggering my
.click(function ()
.

How can I trigger a function when the button is clicked, or when it's tabbed over to and you hit enter?

See this demo: https://jsfiddle.net/kpkammer/ftdez3rb/

UPDATE

I don't want enter anywhere on the page to trigger this function, just when the button is highlighted and you hit enter on the highlighted link

Answer

Click only handles mouse clicks and Taps. To detect enter, you'll need to add the following to handler:

$('#add_row').click(function () {
	console.log("add");
});
$('#add_row').keypress(function(e) {
    if(e.which == 13) {
        console.log("add");
    }
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<input /><br>
<a id="add_row" class="btn btn-default pull-left" tabindex="0">Add Row</a>

This will check when a user presses enter on the button. To combine both into a single method, you can use:

$('#add_row').on('click keypress', function(e) {
  if (e.type == 'click' || e.which == 13) {
    console.log('add');
  }
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<input /><br>
<a id="add_row" class="btn btn-default pull-left" tabindex="0">Add Row</a>