根据GET参数选择选项

时间:2015-03-09 09:39:17

标签: javascript jquery

我有select

<form method="get" id="searchform" action="" role="search">
    <select name="m" onchange="this.form.submit()" title="Archive">
        <option value="201503"> march 2015 </option>
        <option value="201501"> january 2015 </option>
    </select>
</form>

以下jQuery:

var archive = getParameterByName('m');
jQuery('select option[value="' + archive + '"').attr('selected', true);

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

该函数从我放入var m的URL中得到了参数archive的值。唯一不做的是设置从相应选项中选择的属性。

即。如果网址包含?m=201501,我希望<option value="201501"> january 2015 </option>成为<option value="201501" selected>january 2015</option>,以便在select中选择

我错过了什么?

2 个答案:

答案 0 :(得分:1)

你必须像这样设置select标签的值:

var archive = getParameterByName('m');
jQuery('select').val(archive);

实施例: https://jsfiddle.net/syuswwfs/

答案 1 :(得分:0)

使用此功能:

function getUrlParam(sParam)
{
    var sPageURL = window.location.search.substring(1);
    var sURLVariables = sPageURL.split('&');
    for (var i = 0; i < sURLVariables.length; i++) 
    {
        var sParameterName = sURLVariables[i].split('=');
        if (sParameterName[0] == sParam) 
        {
            return sParameterName[1];
        }
    }
}

从URL使用中读取参数:

$(document).ready(function(){
    var parameterM = getUrlParam('m');
    //alert(parameterM);
    $("select").val(parameterM); //this is your selected
});