Shniper Shniper - 7 months ago 12
Javascript Question

Call if statement every time an input is changed

I want to make it so that in my form the user cannot click the submit button until every field has an option selected. I originally tried this with a while loop and it created an infinite loop. I converted it to an if statement and added code to call the if statement every time something on the form is changed, but still the submit button never becomes clickable.

DEMO

if(($('input[type=text]').val() === '') || (!($('input[name=class]').is(':checked'))) || (!($('input[name=race]').is(':checked')))) {
$(' input[type=submit]').css('pointer-events', 'none');
}
else{
$(' input[type=submit]').css('pointer-events', 'auto');
}

$('input[name=user]', 'input[name=race]', 'input[name=class]').change(function(){
if(($('input[type=text]').val() === '') || (!($('input[name=class]').is(':checked'))) || (!($('input[name=race]').is(':checked')))) {
$(' input[type=submit]').css('pointer-events', 'none');
}
else{
$(' input[type=submit]').css('pointer-events', 'auto');
}
});

Answer

A better and shorter way to accomplish your task.

$('form#newPlayer').submit(function(){ // bind form submit event
   if($('input:text').val() == "" || !$('input[name="class"]:checked').length || !$('input[name="race"]:checked').length)
   {
     alert("all fields required");
     return false; // prevent form submission.
   }
});

DEMO