coder87
coder87

Reputation: 101

Angular validations - Enabling/Disabling input fields changes validity of form

I have a form. In which I have input fields and I am doing some validation based on input. Also, there is a submit button which enables only if form is valid.

In this form I am enabling/disabling input field in one of the flow. Initially, when the fields are enable and empty, create button is disabled. After i disable and enable the fields, create button becomes enabled. Although input fields are still empty. More over button which is enabling/disabling this part is outside of this form.

Here is my code

`

<form method="post" novalidate id="example-widgets-form" name="mdnsCtrl.createSubDomainForm" valdr-type="SubDomain">
<div>
    <label>Domain Name</label>
    <input required type="text" name="subDomainName" placeholder="Domain Name" ng-model="mdnsCtrl.newDomain.name">
</div>
<div>
    <label>Description</label>
    <input type="text" name="subDomainDescription" placeholder="Description (Optional)" ng-model="mdnsCtrl.newDomain.description">
</div>
    <button type="button" aria-label="Create" ng-click="mdnsCtrl.createDomain();" 
    ng-disabled="mdnsCtrl.createSubDomainForm.$invalid">
        <span class="ng-scope">Create</span>
    </button>
</div>
</form>

Tried few things like using $setUntouched() and $setPristine(). But nothing is working. Any help will be appreciated.

Adding a codepen example for this: code

Much Thanks. `

Upvotes: 1

Views: 930

Answers (2)

Maxim Shoustin
Maxim Shoustin

Reputation: 77904

Its not good practice to mix Angular with jQuery. Please read this great post: “Thinking in AngularJS” if I have a jQuery background?

You can easily achieve requested behavior by using ng-disabled="mdnsCtrl.formDisabled"

JS

var ctrl = this;  
  ctrl.formDisabled = false;

  this.disable = function(){
    ctrl.formDisabled = true;  
  };

  this.enable = function(){
    ctrl.formDisabled = false;
  };

HTML

<div>
    <label>Domain Name</label>
    <input class="input-field" required type="text" name="subDomainName" placeholder="Domain Name"
           ng-disabled="mdnsCtrl.formDisabled"
           ng-model="mdnsCtrl.name" >
</div>
<div>
    <label>Description</label>
    <input class="input-field" type="text" name="subDomainDescription"
            ng-disabled="mdnsCtrl.formDisabled"
           placeholder="Description (Optional)" ng-model="mdnsCtrl.description">
</div>

Fixed Demo Codepen

Upvotes: 2

Raghav
Raghav

Reputation: 1229

I think you missed required attribute for Description input..

<input type="text" name="subDomainDescription" required ng-model="mdnsCtrl.newDomain.description">

Upvotes: 0

Related Questions