PurpleVermont
PurpleVermont

Reputation: 1241

Trigger when user hits enter but not when focus is lost

I am trying to trigger an event when the user types a search string and hits enter. I don't want to trigger it when the input loses focus (as this may happen when the user clicks other buttons for search options). Both

$("#search-input input").val("").change(function () {

and

$("#search-input input").val("").on('change', function () {

trigger both when the user types something and hits enter, but also when the user clicks on something outside the search box. What would be the correct trigger for what I am trying to do?

Upvotes: 0

Views: 199

Answers (2)

ry4nolson
ry4nolson

Reputation: 859

$("#search-input input").val("").on("keypress", function(e){
  if(e.which==13){
    //handle it here.
  }
});

Upvotes: 1

Dij
Dij

Reputation: 9808

you can use keypress event and check if enter key is pressed. something like this:

$(document).on("keypress", "#search-input input", function(e) {
     if (e.which == 13) {
         //do some stuff
     }
});

Upvotes: 1

Related Questions