user5795637
user5795637

Reputation:

Run Search on keypress

So I have this API call to Wikipedia which works on button click, but I want to search it on enter press as well. I have tried something like this but got stuck..any help appreciated.

$('#search').keydown(function (e) {
    if (e.which == 13) {
        $("#searchTerm").click();
    }
})

Here's the fiddle:

https://jsfiddle.net/ut88e0y3/

Upvotes: 0

Views: 2113

Answers (3)

Haroldo_OK
Haroldo_OK

Reputation: 7270

You should attach the event to the <input>, not to the <button>.

$('#searchTerm').keydown(function (e) {
    if (e.which == 13) {
        $("#search").click();
    }
});

Or, if you prefer attaching to the document:

$(document).on('keydown', '#searchTerm', function (e) {
    if (e.which == 13) {
        $("#search").click();
    }
});

See: https://jsfiddle.net/tbnexLd8/

Upvotes: 0

Ahmed Salama
Ahmed Salama

Reputation: 2825

you should use keypress with the document like this:

    $(document).keypress(function(e) {
        if(e.which == 13) {
            if($('#search').is(':focus')){
                $('#searchTerm').click();
            }
        }
    });

see your example after edit here: https://jsfiddle.net/IA7medd/7j6h1jv7/

Upvotes: 2

Aynolor
Aynolor

Reputation: 413

Instead of listen each keypress, you can use <form> element and submit event. Check this fiddle.

Upvotes: 2

Related Questions