Wesleyvans Wesleyvans - 5 months ago 25
jQuery Question

Check to make sure all fields are filled Jquery

I'm trying to make an easy validator in jquery for my input fields.
Currently i got the following:

function checkInputs(){
var isValid = true;
$('.input-required').each(function() {
if($(this).val() === ''){
isValid = false;
return false;
}
});
return isValid;
}


And then i got a button right that is this:

$('#confirm').click(function () {
alert(checkInputs());
});


But this always returns true even if the input is empty.
Also after this works am going to make to where if all inputs are filled in, a button will be enabled to click on.

edited it so it has a selector now, still getting always true.

Thanks in advance

Answer Source

Try use the filter attribute to get the inputs that has a required attribute.

$('input').filter('[required]')

Added code to check if inputs are filled and enable or disable button. Note if we use this, there aint much point of the $('#confirm').click(function()); function since this button will only be enabled when the inputs are filled.

function checkInputs() {
  var isValid = true;
  $('input').filter('[required]').each(function() {
    if ($(this).val() === '') {
      $('#confirm').prop('disabled', true)
      isValid = false;
      return false;
    }
  });
  if(isValid) {$('#confirm').prop('disabled', false)}
  return isValid;
}

$('#confirm').click(function() {
  alert(checkInputs());
});

//Enable or disable button based on if inputs are filled or not
$('input').filter('[required]').on('keyup',function() {
checkInputs()
})

checkInputs()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <input required>
  <input required>
  <input required>
  <button id="confirm">check</button>
</form>