Tuesday, 26 April 2016

Disable submit button until all mandatory fields are filled - Angular

Here I am going to explain how we can disable a submit button using a simple reusable directive until all the mandatory fields are filled. I have explained same using Angular 2 concept as well, please check this link for that. Let us start with a simple form first

Html


<div ng-app="sampleapp">
    <div ng-controller="samplecontoller" >
     <form name="form" disable-btn ng-submit="submitForm()">
       <div>
          <input type="text" ng-model="model.name" required></input>
      </div>
      <div>
        <input type="number" ng-model="model.number" required></input>
       </div>
      <div>
        <button class="btn btn-primary" type="submit">Submit</button>
      </div>
    </form>  
    </div>
</div>


In the above html "disable-btn" is the directive which we are going to create. I have marked both fields are mandatory using required attribute. Let us start with our directive.

Angular directive for disabling submit button



angular.module('sampleapp').directive('disableBtn',
function() {
 return {
  restrict : 'A',
  link : function(scope, element, attrs) {
   var $el = $(element);
   var submitBtn = $el.find('button[type="submit"]');
   var _name = attrs.name;
   scope.$watch(_name + '.$valid', function(val) {
    if (val) {
     submitBtn.removeAttr('disabled');
    } else {
     submitBtn.attr('disabled', 'disabled');
    }
   });
  }
 };
}
);


We are done with our directive, now you can see that submit button will be disabled until all the mandatory fields are filled. Check the below fiddle and see how it is working.

Using the same directive you can handle pattern validation as well. Also you can set max length/min length. For example see the below sample form.


<input type="number"placeholder="Last Name"  ng-model="model.age" required></input>

<input type="text" ng-model="model.city" ng-minlength="2" ng-maxlength="20" required>

<input type="text" ng-model="model.phoneNumber" pattern="^(?=.*?[1-9])[0-9()-]+$" 
maxlength="25" placeholder="Phone Number" />  

Related Posts

1. Angular js client side pagination like google.

2. Angular Loader using font awesome icons

3. Angular js add class to active element


2 comments :

  1. I have tried but the above code is not working...

    ReplyDelete
    Replies
    1. Attached fiddle is a working copy. Copy your code in fiddle and try , it should work.

      Delete