Search code examples
jqueryselectchained

best way to set a default value based on chained select


im using two selects (chained) and each select has values of site and type, 3 sites, and 2 types. so Im setting a default value for the text input based on which is selected, I am going this route

if ("car" == $("#type").val() && "bmw" == $("#site").val()) $("#id").val('1565');
if ("truck" == $("#type").val() && "bmw" == $("#site").val()) $("#id").val('1565');

for example for the bmw site, and this would be repeated for the 2 other sites.

is a better way to go about this other than 6 if statements?


Solution

  • How about making use of nested associative array - basically define your data then look it up...

    var data = {
        car: {
            bmw: 1565,
            ford: 1900
        },
        truck: {
            bmw: 1565,
            volvo: 2001
        }
    }
    
    var typeValue = $("#type").val();
    var siteValue = $("#site").val();
    
    var dataValue = data[typeValue][siteValue];
    
    if (dataValue) {
        $("#id").val(dataValue);
    }