简体   繁体   中英

Is there an elegant way to check multiple conditions?

I have multiple dropdown menus namely part_no,part_category,make and model. I am trying to display the quantity of vehicle parts in my inventory.

Given that as I become more specific by supplying more values to the dropdown menu, the less type of part has to be displayed. (Something like a filtering)

A good example that I am trying to mimick are the dropdown menus found in this website: http://www.sgcarmart.com/used_cars/listing.php?MMO=Mini&RPG=20&MOD=Austin

Is there a better way of doing the checking(through all possible combinations) rather than doing this:

         //Values from my dropdown menus
           var carmake= $('#car_make').val();
           var carmodel= $('#car_model').val();
           var partname= $('#part_name').val();
           var partcategory= $('#part_category').val(); 

           if(carmake==data['carmake'])
           {
           //do something
           }
           else if (carmake==data['carmake'] && partname==data['partname'])
           {
            //do something           
           }
           else if (carmodel==data['carmodel'] && partname==data['partname'])
           {
            //do something           
           }
           else if (carmodel==data['carmodel'] && partname==data['partname'] &&partcategory==data['partcategory'])
           {
            //do something           
           } else if (carmodel==data['carmodel'] && partname==data['partname'] &&partcategory==data['partcategory' &&partname==data['partname'])
           {
            //do something           
           }
           .
           .
           .
           .
           .              

Put all your test values in an object whose property names are the same as in data . Then loop over all the properties to see if they're all the same:

var search = {
    carmake: $("#car_make").val(),
    carmodel: $("#car_model").val(),
    partname: $("#part_name").val(),
    partcategory: $("#part_category").val()
};

var match = true;
$.each(search, function(prop, value) {
    if (value !== "" && value != data[prop]) { // only compare if the dropdown was selected
        match = false;
        return false; // break out of the loop
    }
});

if (match) {
    // do something
}

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