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

3

8

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.

Manservant answered 30/4, 2015 at 19:16 Comment(0)
C
13

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.
Concerto answered 30/4, 2015 at 19:32 Comment(0)
N
2

One option is to use a variable instead of calling a function.

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

and in your controller, you can set the isRequired variable to true or false in your condition1() and/or condition2() functions.

function myController($scope){
  $scope.isRequired = false;  // initialize it

  $scope.condition1 = condition1;
  $scope.condition2 = condition2;

  function condition1(){
    var returnValue = false;
    // Do some testing that sets returnValue true or false    
    $scope.isRequired = returnValue;
    return returnValue;
  }

  function condition2(){
    var returnValue = false;
    // Do some testing that sets returnValue true or false    
    $scope.isRequired = returnValue;
    return returnValue;
  }
}

Obviously this is not bullet-proof code. But it's a start.

Neilson answered 30/4, 2015 at 19:32 Comment(0)
P
1

I'd suggest you need to use ng-if which will remove the element from form or you can say DOM if condition is not satiesfied. you code will become like

<div>
    <div>
        <input type="text" name="field"
            ng-if="condition1() && condition2()" required>
    </div>
</div>
Pasho answered 30/4, 2015 at 19:29 Comment(2)
using ng-if instead of ng-show, that's the solution. see aboveManservant
@Manservant did you checked the time..when I added answer..exactly 3 mins earlier than youPasho

© 2022 - 2024 — McMap. All rights reserved.