Professor B Professor B - 3 months ago 15
jQuery Question

Disable submit button with text input and select dropdown

I am trying to disable the submit button until all fields have values. It works for the email and password inputs but not for the select dropdown.

I understand it's due to

.keyup()
not applying to a dropdown, but not sure how to adjust the code. I've tried using the
change()
event instead, but that disabled the submit button completely.

<form>
<input class="disableButton" id="email" type="email" />
<input class="disableButton" id="pass" type="password" />
<select id="state" class="selected-state disableButton">
<option value="">State</option>
<option value="AL">AL</option>
<option value="AK">AK</option>
...
</select>
<input id="emailPassSubmit" type="button" disabled="disabled" />
</form>

<script>
$(function() {
$('.disableButton').keyup(function() {
if ($('#email').val() == '' || $('#pass').val() == '' || $('#state').val() == '') {
$('#emailPassSubmit').prop('disabled', true);
} else {
$('#emailPassSubmit').prop('disabled', false);
}
});
});
</script>

Answer

You need to test for both keyup() and change() events as you're wanting to trigger it on different kinds of elements.

You can use jQuery's on() method to attach multiple events to element(s), like so:

$('.disableButton').on('keyup change', function(){ ...

jsFiddle here