[英]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"> Apartment</option>
<option value="villa"> Villa</option>
<option value="all-commercial">All Commercial</option>
<option value="office"> Office</option>
<option value="retail"> 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' : ''; ?>> Apartment</option>
<option value="villa" <?php echo $term == 'villa' ? 'selected' : ''; ?>> Villa</option>
<option value="all-commercial" <?php echo $term == 'all-commercial' ? 'selected' : ''; ?>>All Commercial</option>
<option value="office" <?php echo $term == 'office' ? 'selected' : ''; ?>> Office</option>
<option value="retail" <?php echo $term == 'retail' ? 'selected' : ''; ?>> 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.