Easiest approach using Javascript:
var val = location.href.match(/[?&]term=(.*?)[$&]/)[1]; // get params from URL
$('#saleTerm').val(val); // assign URL param to select field
PHP way refer to answer by Danijel.
Question
What's the best method to output "selected" for my form select based on the URL parameter?
In my URL I might have this parameter &term=retail.
How could I tell the below code to select the retail option?
<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>
Solution
Easiest approach using Javascript:
var val = location.href.match(/[?&]term=(.*?)[$&]/)[1]; // get params from URL
$('#saleTerm').val(val); // assign URL param to select field
PHP way refer to answer by Danijel.
OTHER TIPS
The PHP way:
<?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>
you can do using jquery this way:
var term= GetURLParameter('term');
$('#saleTerm').val(term);
Here is generic function 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];
}
}
}
See more Details HERE