1

I need to check the values of an empty querystring but I'm doing something wrong :( When the url is index.php for exemple I need it to open the #home but if it is index.php?m=1&s=1 it open #page_1_1

    function getUrlVars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}
var m = getUrlVars()["m"];
var s = getUrlVars()["s"];

if((m!='')&&(s!='')){
    $('#page_'+m+'_'+s+'').show();
}
    else{ $('#home').show(); }
4
  • what is the problem?, alert(m), alert(s), what value are showing? Commented Oct 31, 2013 at 2:40
  • I dont know what the function get when is an empty querystring, I've tried '', '0', null but it's not working Commented Oct 31, 2013 at 2:43
  • seems fine jsfiddle.net/arunpjohny/nmddf/1 Commented Oct 31, 2013 at 2:46
  • check where u are using vars[hash[0]]=hash[1], because hash[0] is 'm' and hash[1] is '1&s' Commented Oct 31, 2013 at 2:52

1 Answer 1

1

m & s will be undefined if the query string is empty or does not contain those values. You need to change your check to the following:

if(m && s) {
    $('#page_'+m+'_'+s+'').show();
} else {
    $('#home').show();
}

The if statement above will evaluate to false if m or s are omitted from the query string, or if either of them are empty (e.g. http://www.somewhere.com?m=1&s=)

Sign up to request clarification or add additional context in comments.

1 Comment

Note that the test will fail if m or s is an empty string on the url, because if('') evaluates to false. This might not apply to your case, but it's worth mentioning.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.