Disabled submit button if form is invalid angularjs

Shnick

I currently have a form with many different inputs. In the example below I have created a form with two inputs for simplicity. I am trying to make it so my submit button is disabled when the form isn't valid - that is, when all the required inputs have not been filled out.

This is what I have tried so far:

angular.module('myApp', []);
angular.element(document).ready(function () {
  angular.bootstrap(document, ['myApp']);  
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.min.js"></script>

<form name="myForm">
  <input type="text" placeholder="name" required/>
  <input type="number" placeholder="age" required />
  <input type="submit" ng-disabled="myForm.$invalid" />
  {{ myForm.$invalid }} <!-- prints "false" -->
</form>

As you can see from the above snippet, myForm.$invalid is false even though I haven't filled out the required inputs yet. Is there some different property which will tell me if the required inputs have all been filled out?

I have looked at different posts such as this one but when I try and use myForm.$valid it just gives me the negated version of myForm.$invalid, which doesn't help much either.

Saurabh Agrawal

You are missing ng-model in the form fields. You need to add ng-model as it detects the changes in the form fields.

Try this:

angular.module('myApp', []);
angular.element(document).ready(function () {
  angular.bootstrap(document, ['myApp']);  
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.min.js"></script>

<form name="myForm">
  <input type="text" ng-model="name" placeholder="name" required/>
  <input type="number" ng-model="age" placeholder="age" required />
  <input type="submit" ng-disabled="myForm.$invalid" />
  {{ myForm.$invalid }} <!-- prints "false" -->
</form>

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related