Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine whether form input has focus

I'm doing validation in AngularJS, and I have a div that is displayed if there are 3 types of errors.

For required I want to show the error message only if the page is submitted with empty value

<div class="error" data-ng-show="submitted && mainForm.email.$error.required" /> 

For the regex validation I want it to flag real-time, default behavior.

<div class="error" data-ng-show="mainForm.email.$error.pattern" /> 

The problem I'm facing is with minlength. I don't want to show it while they are typing. It's annoying because they haven't finished typing. I don't want to display it on submit either, I think that's too late. I'd like to show it when they are no longer in focus of the element.

If //mainForm.email.$focus existed I could simply do this

<div class="error" data-ng-show="mainForm.email.$error.minlength &&  !mainForm.email.$focus"/> 

Anyone know of any way to do this kind of check or any non drawn out alternative?

Thanks!

like image 547
Proximo Avatar asked Aug 03 '14 21:08

Proximo


People also ask

How do you know if input field has focus?

HTML DOM Document hasFocus() The hasFocus() method returns a true if the document (or any element in the document) has focus. Otherwise it returns false .

How do you know element is focused or not?

To check whether a specific element has focus, it's simpler: var input_focused = document. activeElement === input && document. hasFocus();

How do I find out which DOM element has the focus?

Syntax: var ele = document. activeElement; Return value: It returns the currently focused element in the document.

How do you know if an element is focused angular?

hasFocus() : whether the document or any element inside the document has focus. document. activeElement : Property containing which element currently has focus.


1 Answers

Yes it does
you can use ngFocus and ngBlur for this purpose

here is the code

<form name="mainForm">     <span ng-show="mainForm.email.$error.pattern && !focus">error here</span>     <input name="email" ng-pattern="..." ng-focus="focus=true" ng-blur="focus=false" type="text" /> </form> 

ngFocus and ngBlur take expression and ngShow shows upon true evaluation

like image 59
Ravi Sahu Avatar answered Sep 21 '22 15:09

Ravi Sahu