Dropdown selected based on URL parameter - PHP or jQuery?

北城以北 提交于 2020-01-02 03:26:32

问题


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>

回答1:


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.




回答2:


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>



回答3:


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



来源:https://stackoverflow.com/questions/23591754/dropdown-selected-based-on-url-parameter-php-or-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!