check every input has value

Html

<input type="text" name="test[]" class="test">

How can I check every input has value? This is what I tried but if one the input has value it will not alert the message

Script

var x = new Array();
var message = "";

jQuery("input[name='test[]']").each(function(){
  var y = jQuery(this).val().toLowerCase();
  if(y){
    x.push(y);
  }
});

if(x.length === 0){
  message += "missing";
};

if(message != ""){
  alert(message);
}

EDIT I want to alert if one of input has no value

Upvotes: 1

Views: 1168

Answers (1)

Michael Coker
Michael Coker

Reputation: 53709

This will alert 'no value' if one of the inputs has no value. Just check the $.val() and alert and break the loop if it doesn't return anything.

$('button').on('click', function() {

  $("input[name='test[]']").each(function() {
    if (!$(this).val()) {
      alert('no value');
      return false;
    }
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="test[]" class="test">
<input type="text" name="test[]" class="test">
<input type="text" name="test[]" class="test">
<button>validate</button>

Upvotes: 2

Related Questions