Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set required attribute for an input element if it's not hidden

I'm working on a dynamic form using angular.js. Inputs field

<div ng-show="condition()">
    <input type="text" name="field" required>
</div>

If condition() returns false, the input field won't be shown. But by clicking on a submit button, I'll get on chrome, the message:

An invalid form control with name='field' is not focusable.

Well, a solution is, to use ng-required:

<div ng-show="condition()">
    <input type="text" name="field" ng-required="condition()">
</div>

Well, here I have to repeat code, using the condition() several times.

It becomes bad, when you can encapsulated ng-show's:

<div ng-show="condition1()">
    <div ng-show="condition2()">
        <input type="text" name="field"
            ng-required="condition1() && condition2()">
    </div>
</div>

Is there a better way, the required tag should be there when the input is visible, and not, if it's hidden.

like image 655
Artisan72 Avatar asked Apr 30 '15 19:04

Artisan72


1 Answers

Instead of using ng-show , use ng-if, because when you use ng-show then that element is still part of DOM.

something like this:

<div ng-if="condition()">
    <input type="text" name="field" required>
</div>

This way you will not get error

An invalid form control with name='field' is not focusable.
like image 97
Mudasser Ajaz Avatar answered Oct 12 '22 15:10

Mudasser Ajaz