1

I've this code below:

<div class="search-container">
    <input id="search-value" type="text" autocomplete="off" ng-model="vm.searchQuery" ng-focus="vm.searchBoxHasFocus = true" ng-blur="vm.searchBoxHasFocus = false" class="search-box-input ng-pristine ng-untouched ng-valid ng-empty" placeholder="Pesquisar" ng-enter="vm.goSearch()" ng-change="vm.getSuggestions()">
    <div class="label-search" ng-click="vm.goSearch()"></div>
    <button type="button" class="reset-search" ng-click="vm.clearQuery()"></button>
</div>

How can I call a JS function when I press "enter" in the input?

closed as off-topic by Gaurravs, Karthik Jaganathan, MHeld, Christoffer, Robert Lindgren Jan 25 at 13:36

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Programming questions not specific to SharePoint are off-topic here, but can be asked on Stack Overflow." – Gaurravs, Karthik Jaganathan, MHeld, Christoffer, Robert Lindgren
If this question can be reworded to fit the rules in the help center, please edit the question.

3

You could do it with these changes:

Add the following attribute to the input field: ng-keypress="vm.myFunction($event)"

Add the following function to your vm object:

myFunction = function (keyEvent) {
            if (keyEvent.which === 13) {
                //enter pressed - here goes your code
            }
        }

EDIT based on the comment: You could also add the following attribute to the html input field, but you should check this because it could break your existing angularjs directives:

onkeypress="javascript: if(event.keyCode == 13) yourexistingfunction();"
  • Is it possible to do without add more code, only work with what I have? – KmDroid Jan 24 at 21:35
2

For AngularJS, we need add a directive, like this:

app.directive('ngEnter', function () {
    return function (scope, element, attrs) {
        element.bind("keydown keypress", function (event) {
            if(event.which === 13) {
                scope.$apply(function (){
                    scope.$eval(attrs.ngEnter);
                });

                event.preventDefault();
            }
        });
    };
});

Example code: https://jsfiddle.net/lsconyer/bktpzgre/1/

Not the answer you're looking for? Browse other questions tagged or ask your own question.