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">&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>
Was it helpful?

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' : ''; ?>>&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>

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top