Pergunta

I have a Bootstrap 3.0 button on a web page. The button is not part of a form. When this page renders, I would like for the button to be clicked if the user hits return on the keyboard. I have a Marionette event listener set up to handle the click event.

Here is my button:

<button class="btn btn-primary js-new pull-right">New facility</button>

How do I do this?

I have tried several things - including what I thought was the obvious solution: executing $(".js-new").first().focus(). This does not work.

Foi útil?

Solução

If I understand correctly, you'd like to trigger the click handler for a certain button when "return" is hit. If that's the case, this ought to work; $(".js-new").first().click();, assuming your selector is correct.

You can check whether or not your selector is finding an element by using either alert or console.log to display the length of the selector: console.log($(".js-new").length);.

Once you have verified that you have found the correct element, you can trigger whatever click handler(s) are bound to the element by simply calling the .click() function; if no arguments are passed to it, it executes whatever triggers are already on the element.

--

Edit: if you'd simply like to trigger the click handler when enter is pressed, you could bind an event to the return key:

$(document).keypress(function(e) {
    if(e.which === 13) {
        // enter has been pressed, execute a click on .js-new:
        $(".js-new").first().click();
    }
});
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top