I found this question very useful for submitting a form when someone presses the "enter" key:
Javascript:
angular.module('yourModuleName').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': event}); }); event.preventDefault(); } }); }; });
HTML:
<div ng-app="" ng-controller="MainCtrl"> <input type="text" ng-enter="doSomething()"> </div>
What I would like to do know, is to set the field to blur when the "enter" key is pressed. What would doSomething()
look like to blur the sender field?
I would like to leave the ngEnter
directive as it is, since I would like to re-use it for other functions.
Update: I know I can create a whole directive just for blurring (that's how I have it now), but what I'd like to do is be able to do something like this:
<input type="text" ng-enter="this.blur()">
Or how do I pass the current element as a parameter?
<input type="text" ng-enter="doBlur(this)">
If you want to fire blur event with key enter event, then simply pass $event in function and $event. target. blur(); in the function.
A blur event fires when an element has lost focus. Note: As the blur event is executed synchronously also during DOM manipulations (e.g. removing a focussed input), AngularJS executes the expression using scope.
you can easily use blur event in angular 6, angular 7, angular 8, angular 9, angular 10, angular 11, angular 12, angular 13 and angular 14 application. When user will key up on input box field then trigger onBlurEvent() of angular component. we will use (change) attribute for call function.
The blur() method is used to remove focus from a submit button. Tip: Use the focus() method to give focus to a submit button.
After trying a bunch of things, this is seems not possible, as you would need to pass $event to get the target element, so separate directive seems to be the only way to go:
What we desire:
You cannot pass this
because it refers to the scope, so you need to pass the event.
<input type="text" ng-enter="doBlur($event)">
Once you have the event, you can get the target from it.
$scope.doBlur = function($event){ var target = $event.target; // do more here, like blur or other things target.blur(); }
But, you can only get pass event in a directive like ng-click ... kinda unsatisfactory. If we could pass $event outside directive, we could blur in that reusable way you requested.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With