根据网址参数为表单选择输出“已选择”的最佳方法是什么?
在我的网址中,我可能有此参数& 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>
答案 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' : ''; ?>> 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>
答案 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