Dataminer
Dataminer

Reputation: 39

Multiple conditions / disable select options with JS or JQuery?

According to this fiddle (http://jsfiddle.net/Qu44s/) I'm trying to have more conditions than just 2 select fields -> http://jsfiddle.net/tet8M/ but don't know how to do it. :(

For example:

Green -> XS -> Femal -> V-Neck, U-Neck

Blue -> S, M -> Male, Female -> V-Neck

Yellow -> L, XL -> unisex -> short-arms, long-arms

Sorry, I'm absolutly not fit in JS or JQ, but perhaps someone has an idea how to solve this.

Thanks for any help!

Upvotes: 1

Views: 728

Answers (1)

Antony
Antony

Reputation: 15106

Simply extend what you have and disable the irrelevant options.

See DEMO.

var availableSizesForColors = {
    '2': ['6'],
    '3': ['7', '8'],
    '4': ['9', '10']
};

var availableGendersForColors = {
    '2': ['13'],
    '3': ['12', '13'],
    '4': ['14']
};

var availableExtrasForColors = {
    '2': ['18', '19'],
    '3': ['18'],
    '4': ['16', '17']
};

$('#color').change(function() {
    var availableSizes = availableSizesForColors[this.options[this.selectedIndex].value];
    var availableGenders = availableGendersForColors[this.options[this.selectedIndex].value];
    var availableExtras = availableExtrasForColors[this.options[this.selectedIndex].value];
    $('#size option').prop('disabled', function () { return $.inArray(this.value, availableSizes) == -1 });
    $('#sex option').prop('disabled', function () { return $.inArray(this.value, availableGenders) == -1 });
    $('#extra option').prop('disabled', function () { return $.inArray(this.value, availableExtras) == -1 });
});

Disable the rest of the form if color is not selected.

$('#color').change(function() {
    $('#size').val('5');
    $('#sex').val('11');
    $('#extra').val('15');
    if (this.options[this.selectedIndex].value == 1) {
        $('#size,#sex,#extra').attr("disabled", "disabled");
    } else {
        $('#size,#sex,#extra').removeAttr("disabled");
    }
});
$('#color').trigger('change');

Upvotes: 2

Related Questions