简体   繁体   中英

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?

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();

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM