Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dropdown selected based on URL parameter - PHP or jQuery?

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>
like image 502
NotAnotherCliche Avatar asked May 11 '14 10:05

NotAnotherCliche


3 Answers

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.

like image 51
Dave Avatar answered Oct 16 '22 09:10

Dave


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>
like image 8
Danijel Avatar answered Oct 16 '22 08:10

Danijel


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

like image 4
Ehsan Sajjad Avatar answered Oct 16 '22 09:10

Ehsan Sajjad