1

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.

1
  • add a class which has disabled css property. Add and call a method , which is defined in controller , from each input box on change and valid the form if all input fields are valid then remove the class dynamically or add the class. Commented Dec 29, 2019 at 4:38

1 Answer 1

3

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.