Question

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>
Was it helpful?

Solution

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

OTHER TIPS

You forgot to add the disableButton class to the select drop down.

Here is a working version:

http://jsbin.com/gonut/1/

The selected answer works, but it's not elegant or scalable. Each field is hard-coded for some reason, even though you already went to the trouble of adding a class for each required input.

Instead, just cycle through each item with the class '.disableButton':

$('.disableButton').on('keyup change', function() {
    var empty = false;
    $('.disableButton').each(function() {
        if ($(this).val() == '') {
            empty = true;
        }
    });

    if (empty) {
        $('#emailPassSubmit').prop('disabled', true);
    } else {
        $('#emailPassSubmit').prop('disabled', false);
    }
});

Just make sure that each field (works with text input, drop down, etc) has the class "disableButton". Also, drop downs must have the default value of "", which yours does.

This way, in the future, you could add as many fields as you like and as long as you had the correct class, you don't have to touch this code at all.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top