简体   繁体   中英

Struts-JQuery Disable drop down option based on a selection of a different drop down

In my JSP I have a form with multiple drop down items. This is a form using the struts-tags declaration.

On this form, I want to disable one or more options of one drop down based on the selection of a separate drop down on the same form.

Here's a simple example to demonstrate. This is how I have my drop downs coded.

<s:select id="vehicleType" name="vehicleType" list="#{'0': 'Truck','1':'Sedan'}"

<s:select id="vehicleList" name="vehicleList" list="#{'0':'Ford F150','1':'Dodge Ram','2':'Honda Accord','3':'Nissan Altima'}"

If I select "Truck" from the "vehicleType" drop down, I want to disable both "Honda Accord" and "Nissan Altima" from the "vehicleList" drop down. If I select "Sedan" from the "vehicleType" drop down, I want to disable both "Ford F150" and "Nissan Altima" from the "vehicleList" drop down.

Try the following:

function resetVehicleList(vehicleType)
{
    $('#vehicleList option').show();
    if($(vehicleType).val() == '0')
    {
        $('#vehicleList option[value="2"]').hide();
        $('#vehicleList option[value="3"]').hide();
    }
    else if($(vehicleType).val() == '1')
    {
        $('#vehicleList option[value="0"]').hide();
        $('#vehicleList option[value="1"]').hide();
    }
    $('#vehicleList').val($('#vehicleList option:visible').first().attr('value'));
}

$('#vehicleType').change(function(){
    resetVehicleList(this);
});

$(document).ready(function(){
    resetVehicleList($('#vehicleType'));
});

Try the following code to disable the options:

$("#vehicleType").on('change', function() {
    var vlist = $("#vehicleList");
    vlist.find('option').prop('disabled', false);

    if (this.value === "0") {
        vlist.find('option[value="2"]').prop('disabled', true);
        vlist.find('option[value="3"]').prop('disabled', true);
    }
    else if (this.value === "1") {
        vlist.find('option[value="0"]').prop('disabled', true);
        vlist.find('option[value="1"]').prop('disabled', true);
    }

});

Demo: http://jsfiddle.net/mfd13w6u/

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