简体   繁体   中英

compare a select option value and a value from URL

I have a select tag to choose categories, each option contain the category number as value. The category number is in the URL string. I'm trying to write a JS to check if the option value is the same as the category number in the URL and if so make the option selected. so far the script dosnot work. What am I doing wrong?

here is the code:

function GetUrlValue(VarSearch){
    var SearchString = window.location.search.substring(1);
    var VariableArray = SearchString.split('&');
    for(var i = 0; i < VariableArray.length; i++){
        var KeyValuePair = VariableArray[i].split('=');
        if(KeyValuePair[0] === VarSearch){
            return KeyValuePair[1];
        }
    }
}
function compareValue(){
    var x = document.getElementById("selectcategory").length;
    for (var i = 0; i < x; i++){
        var categNo = document.getElementById("selectcategory").options[i];
        var UrlValue1 = GetUrlValue('icid');
        if (categNo === UrlValue) {
            document.getElementById("selectcategory").options[i].selected = true;
        }
        alert(UrlValue1);
    }
}

if needed, I will send a link to the work. if doing that with jquery is easier, i will be happey to learn.

thanx.

The problem is that categNo should be the value of the corresponding option tag. Also it's better to cache select element and not requery DOM in the loop:

function compareValue() {

    var select = document.getElementById("selectcategory");
    var x = select.options.length;

    for (var i = 0; i < x; i++) {
        var categNo = document.getElementById("selectcategory").options[i].value;
        var UrlValue = GetUrlValue('icid');
        if (categNo === UrlValue) {
            select.options[i].selected = true;
        }
    }
}

Demo: http://jsfiddle.net/dj7c6sdL/

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