簡體   English   中英

根據URL參數 - PHP或jQuery選擇下拉列表?

[英]Dropdown selected based on URL parameter - PHP or jQuery?

根據URL參數為表單選擇輸出“selected”的最佳方法是什么?

在我的URL中,我可能有這個參數&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>

使用Javascript最簡單的方法:

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

PHP方式參考Danijel的回答。

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>

你可以這樣使用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];
            }
        }
    }​

點擊此處查看更多詳情

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM