简体   繁体   中英

Can this javascript be shortened? Jquery is an option

The idea is when each select field is changed, it will pass part of the directory needed for the form action (the value of each option). ie:

<select onChange="chgFrmAtn" id="1-1">
 <option value="">Any</option>
 <option value="exDir1Option1">option 1</option>
 <option value="exDir1Option2">option 2</option>
</select>

So here is the javascript, basically I want to build 2 directories, several different options. The number of options is much longer than the list in this example script. The options can be in any order. if any is selected, it doesn't add to the directory.

function chgFrmAtn( itemVal )
{
    var directory1Part1 = '';
    var directory1Part2 = '';
    var directory1Part3 = '';

    var directory2Part1 = '';
    var directory2Part2 = '';

    if(itemVal == '1-1'){
        directory1Part1 = document.getElementById(itemVal);
    }
    if(itemVal == '1-2'){
        directory1Part2 = document.getElementById(itemVal);
    }
    if(itemVal == '1-3'){
        directory1Part3 = document.getElementById(itemVal);
    }
    if(itemVal == '2-1'){
        directory1Part1 = document.getElementById(itemVal);
    }
    if(itemVal == '2-2'){
        directory1Part2 = document.getElementById(itemVal);
    }
    document.advancedSearchForm.action = directory1Part1 + directory1Part2 + directory1Part3 + '/' + directory2Part1 + directory2Part2 + '/';
}

Thank you in advance.

try

function chgFrmAtn(itemVal)
{
      document.advancedSearchForm.action = document.getElementById(itemVal).value;
}

basically you will only get one value in your directoryxParty since itemVal will remain same and only one if statement will true.

Edit:

If it has to append values from each select, then

var selectIds = ["1-1", "1-2", "1-3", "2-1", "2-2"];

function chgFrmAtn()
{
     var vals = selectIds.map(function(id){ 
        var obj = document.getElementById(id);
        return obj && obj.value ? obj.value : ""; 
     }); 
     document.advancedSearchForm.action = vals[0] + vals[1] + vals[2] + '/' + vals[3] + vals[4] + '/';
}

You can use two array and map the comparison.

function chgFrmAtn(itemVal) {
    var vals = ['1-1', '1-2', '1-3', '2-1', '2-2'],
        directory = vals.map(function (a) {
            return itemVal === a ? document.getElementById(a) : '';
        });

    document.advancedSearchForm.action = directory[0] + directory[1] + directory[2] + '/' + directory[3] + directory[4] + '/';
}

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