Thursday, 11 October 2018

JS - updating dropdown based on previous dropdown selection

I have an ecommerce site that has products with multiple attributes (e.g. size, colour, etc,.)

On each product page there is a dropdown for each attribute with a class of 'attribute_price'.

I have also preloaded hidden inputs onto the page from my database with the pricing for each product with a class of 'hidden_attribute_value'.

So not every combination of size and colour is an option. For example, we might have 'small_red' or 'medium_red' but no 'large_red'

So if they select 'large' from the size dropdown menu 'red' should not be an option for the colour.

What I have so far is:

$("select.attribute_price").on("change", function(){

    var id = event.target.id;
    // determine which dropdown was changed (size or colour)
    var attribute_value = document.getElementById(id).value+'_';
    // get the value of the dropdown that they selected

    var other_attribute_ids = []
    var i;
    var other_attributes = document.getElementsByClassName("attribute_price");
    for(i=0; i<other_attributes.length; i++){
        if(other_attributes[i].id != id){
            var other_attribute_id = document.getElementById(other_attributes[i].id).id;
            other_attribute_ids.push(other_attribute_id);
        }
    }
    // create an array of all of the other dropdown ids excluding the one they changed

    var all_attribute_ids = []
    var i;
    var all_attributes = document.getElementsByClassName("hidden_attribute_value");
    for(i=0; i<all_attributes.length; i++){
        all_attribute_ids.push(all_attributes[i].id);
    }
    // create an array of all of the possible values that it can be

});

So I have a variable 'attribute_value' which would be something like 'red_' or 'blue_'.

I have an array called 'all_attribute_values' which has the ids of hidden inputs for all possible combinations. These would have values like 'small_red_' or 'small_blue'.

And I have an array called 'other_attribute_ids' which has the id of the other dropdown menus that haven't been selected.

So if an item in 'all_attribute_values' does not contain 'attribute_value' remove that option from 'other_attribute_ids'.

Any help or suggestions with this would be greatly appreciated.



from JS - updating dropdown based on previous dropdown selection

No comments:

Post a Comment