简体   繁体   中英

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?

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>

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM