根据URL参数 - PHP或jQuery选择下拉列表?

时间:2014-05-11 10:59:16

标签: php jquery forms parameters

根据网址参数为表单选择输出“已选择”的最佳方法是什么?

在我的网址中,我可能有此参数& term = retail。

我如何告诉以下代码选择零售选项?

<select class="form-control" name="term" id="saleTerm">
        <option value="all-residential" selected>All Residential</option>
        <option value="apartment">&nbsp;&nbsp;&nbsp;Apartment</option>
        <option value="villa">&nbsp;&nbsp;&nbsp;Villa</option>
        <option value="all-commercial">All Commercial</option>
        <option value="office">&nbsp;&nbsp;&nbsp;Office</option>
        <option value="retail">&nbsp;&nbsp;&nbsp;Retail</option>
</select>

3 个答案:

答案 0 :(得分:7)

使用Javascript最简单的方法:

var val = location.href.match(/[?&]term=(.*?)[$&]/)[1];   // get params from URL
$('#saleTerm').val(val);   //  assign URL param to select field

PHP方式参考Danijel的回答。

答案 1 :(得分:7)

PHP方式:

<?php $term = !empty( $_GET['term'] ) ? $_GET['term'] : ''; ?>

<select class="form-control" name="term" id="saleTerm">
        <option value="all-residential" <?php echo $term == 'all-residential' ? 'selected' : ''; ?>>All Residential</option>
        <option value="apartment" <?php echo $term == 'apartment' ? 'selected' : ''; ?>>&nbsp;&nbsp;&nbsp;Apartment</option>
        <option value="villa" <?php echo $term == 'villa' ? 'selected' : ''; ?>>&nbsp;&nbsp;&nbsp;Villa</option>
        <option value="all-commercial" <?php echo $term == 'all-commercial' ? 'selected' : ''; ?>>All Commercial</option>
        <option value="office" <?php echo $term == 'office' ? 'selected' : ''; ?>>&nbsp;&nbsp;&nbsp;Office</option>
        <option value="retail" <?php echo $term == 'retail' ? 'selected' : ''; ?>>&nbsp;&nbsp;&nbsp;Retail</option>
</select>

答案 2 :(得分:4)

你可以这样使用jquery:

var term= GetURLParameter('term');
$('#saleTerm').val(term);

这是通用函数 GetURLParameter()

function GetURLParameter(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];
            }
        }
    }​

查看更多详情HERE