user94628
user94628

Reputation: 3721

Disable option values in one select dropdown depending on value selected in another

I have a form with two select dropdowns. The first is opening times and the second is closing times. So When the user selects a opening time the closing time cannot be earlier than this.

My Jquery instead disables all the second drop down values instead of only the times earlier as can be seen here: JSFiddle.

    $('#open').change(function(){
        if($('#close').val()<$('#open').val()){
            $('#close').prop('disabled', true);           
        };
    })    

How can I get the behaviour I want?

Upvotes: 0

Views: 1677

Answers (2)

Josh Beam
Josh Beam

Reputation: 19772

Try this (here is the updated jsfiddle):

$('#open').change(function(){
    var that = $(this);

    $('#close option').each(function() {
        if($(this).val() < that.val()) {
            $(this).prop('disabled',true);   
        } else {
            $(this).prop('disabled',false);   
        }
    });
});    

It works on Chrome 36, but not on Firefox (haven't tested any browsers besides those two).

Since this behavior is unreliable, you might try dynamically adding options to the second select element based on whatever is chosen in the first select element.

EDIT

See this jsfiddle based on your original fiddle. It will let you dynamically populate the second select element.

var vals = ['00.00', '00.15', '00.30', '00.45', '01.00', '01.15', '01.15'];

for(var i = 0; i<vals.length; i++) {
    $('#open').append('<option val="'+vals[i]+'">'+vals[i]+'</option>');   
}

$('#open').change(function(){
    $('#close').html('');

    for(var i = 0; i<vals.length; i++) {
        if(vals[i] >= $(this).val()) {
            $('#close').append('<option>'+vals[i]+'</option>');
        }
    }
}).change();

Upvotes: 3

Maurice Perry
Maurice Perry

Reputation: 32831

Most browsers do not allow the disabling of individual <option>s in a <select>. I would fill the second <select> whenever the first is changed.

Upvotes: 1

Related Questions