user3334341
user3334341

Reputation: 1

Need the function to be triggered on hit of enter

I have a search box whch is a text type. it has a click button, which initiates the Find().

how can i do the find by hitting enter inside the textbox

Upvotes: 0

Views: 89

Answers (4)

MBielski
MBielski

Reputation: 6620

I generally have very good luck with Angular-UI. The ui-keypress directive should serve well in this case. http://angular-ui.github.io/ui-utils/#/keypress. The keycode you want for the Return/Enter key is 13.

Upvotes: 0

musically_ut
musically_ut

Reputation: 34288

Use ng-keypress on the input element and check for enter key code:

<input type="text" ng-keypress="($event.which === 13) ? Find() : void(0)" />

This is assuming that jQuery has been loaded. Otherwise, you might want to use $event.keyCode, but doing it in a browser compatible way would be tricky.


If you have a directive which contains this template, then you should catch this event in the link function and call Find there. Otherwise, putting the input button inside a form and defining a on-submit on the form element. Do check for IE compatibility though, I remember IE7 at least needs a hidden <input type="submit" /> in the form for the enter key to submit the form.

Upvotes: 1

juvian
juvian

Reputation: 16068

    document.onkeydown = function(evt) {//when key is pressed

        evt = evt || window.event;
        if (13 == evt.keyCode) {//if key was enter
            if (document.activeElement.className== "search_input"){//if the focus is on your input (in this case search_input)
                Find() //call your function
                return false;//cancel enter
            }
        }   
    }

Upvotes: 0

Jason Fingar
Jason Fingar

Reputation: 3374

If your text input is inside of a form element, you can attach an onSubmit (or jQuery .submit()) event handler to the form element. This event will fire when the user presses enter while inside the text input

Upvotes: 2

Related Questions