user3125591
user3125591

Reputation: 123

Don't submit form if inputs are empty

I have two sets of data: "heat" and "cold", which are retrieved from another provider. This data is quite unorganized and I have removed lots of stuff in the code just to show the essential part of my problem. "Heat" and "cold" both contain properties that the user has to fill in. This property however is dynamic and the amount of properties is not fixed (hence it is in a loop as shown in the code).

My goal is to hide/disable the submit button, which is located all the way down, whenever one single input field in the list in either sets of data is empty. This should also preferably work on Internet Explorer 9, where the 'required' tag is not supported.

I have tried:

Code:

<!--Start wrapper!-->
<div class="wrapper">
  <div ng-repeat="(code, program) in data.old.heat">
    <div class="row" ng-repeat="(componentId, component) in program">  
      <div class="inputForm">
        <!--This field may not be left empty!-->
        <input type="text" class="form" ng-model="component.userInput">
      </div>
    </div>
  </div>

  <div ng-repeat="(code, program) in data.old.cold">
    <div class="row" ng-repeat="(componentId, component) in program">
      <div class="inputForm">
        <!--This field may not be left empty!-->
        <input type="text" class="form" ng-model="component.userInput">
      </div>
    </div>
  </div> 
</div>
<!--End of wrapper !-->

<div class="submitPanel">
  <button ng-click="submit()">Submit</button>
</div>

Upvotes: 2

Views: 5727

Answers (3)

Pepijn
Pepijn

Reputation: 1204

I have two options for you, but they both include ng-disabled (https://docs.angularjs.org/api/ng/directive/ngDisabled).

You can put this attribute on the button and you can either call a function on the scope in that attribute and check if all values are given.

So like: ng-disabled="checkInputs()".

Or

You wrap a form around all your inputs, give the form a name like name=form and set the required attribute on all inputs. (EDIT: you could use ng-required="true" for IE9.)

Then you could say ng-disabled="!form.$valid".

Upvotes: 3

knocked loose
knocked loose

Reputation: 3304

Not specific to angular, but you could check if it has characters via jQuery.

Html

<div class="submitPanel">
  <button class="submit-btn" ng-click="submit()">Submit</button>
</div>

jQuery

$('#form input').blur(function()
{
    if( $(this).val().length === 0 ) {
        $(this).parents('.submit-btn').addClass('hide');
    }
});

CSS

.hide{
display:none;
}

Upvotes: 4

Adam Buchanan Smith
Adam Buchanan Smith

Reputation: 9439

Here ya go : https://jsfiddle.net/DIRTY_SMITH/zxbe5rt0/

function validate(){
var text1 = document.getElementById('text').value;

if (text1.length > 0){
    alert("went through");
    return true;
}
alert("did not go through");
return false;
}

Upvotes: 4

Related Questions