AndySummers2020
AndySummers2020

Reputation: 451

how to get a URL parameter and set the value of a select option on page load?

I'm new to Javascript and I can't find a simple example of this online.

I have a simple HTML page with a select widget on it:

<select name="myProduct">
    <option value="aaa">This is AAA</option>
    <option value="bbb">This is BBB</option>
    <option value="ccc">This is CCC</option>
</select>

What's an easy way to pass a param to the URL like so ...

/mypage.html?selectedProduct=CCC

... and have the value selected in the widget on page load?

Upvotes: 5

Views: 7600

Answers (2)

AndySummers2020
AndySummers2020

Reputation: 451

I got it working like so ...

<html>

<head>
/* .... */
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>

<script type="text/javascript">
    $(function() {
        var selectedProduct = GetURLParameter("selectedProduct");
        if (selectedProduct) {
            $("#myProduct").val(selectedProduct); 
        }
    });
    
    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];
            }
        }
    }
</script>

<body>

<select id="myProduct"> <!-- NOTE that's 'id', not 'name' there -->
    <option value="aaa">This is AAA</option>
    <option value="bbb">This is BBB</option>
    <option value="ccc">This is CCC</option>
</select>

</body

</html>

Upvotes: 0

Scott Marcus
Scott Marcus

Reputation: 65835

Set up a change event handler on the select and append the querystring (that has the value of the select concatenated on to it) to the current URL.

var urlParams = new URLSearchParams(window.location.search);
let queryString = urlParams.get('selectedProduct');

// Find the option in the select that has the same value as
// the query string value and make it be selected
document.getElementById("myProduct").querySelector("option[value='" + queryString + "']").selected = true;
<select id="myProduct">
    <option value="aaa">This is AAA</option>
    <option value="bbb">This is BBB</option>
    <option value="ccc">This is CCC</option>
</select>

Upvotes: 5

Related Questions