Tom
Tom

Reputation: 1263

Button with focus - run function on 'Enter'

I have my code below. It's doing what I want. What I want to also do is run this function when a user use their keyboard to tab to the .add-row button and then presses enter. How do I make that run?

$('body').on('click', '.add-row', function(e) {
  $( this ).html('Hide').removeClass('add-row').addClass('hide-row');
  $( this ).parent().parent().next().show();
});

Upvotes: 0

Views: 137

Answers (1)

willwolfram18
willwolfram18

Reputation: 1887

My understanding is you want the button to have focus and the user to press enter to fire the event, yeah? If so, then using the :focus pseudo class selector on the .add-row should work with the keypress event

$("body").on("keypress", ".add-row:focus", function(e) {
    var ENTER_KEY_CODE = 13;
    if (e.keyCode === ENTER_KEY_CODE)
    {
        alert("Enter key pressed");
        // perform hide row and other operations here
    }
});

Upvotes: 1

Related Questions