3

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?

AndySummers2020
  • 411
  • 1
  • 6
  • 14
  • You can use: `window.location.search.split("=")[1]` that will return, in your example, `CCC`. Then: `document.getElementById("myProduct")` (you'll have to add `id`, or use `document.getElementsByName("myProduct")[0]` - if you only have one), then iterate over the options, compare value to lowerCase of CCC and set selected. you'd have to do more work on `window.location.search` if you're passing more var/val pairs. Oh, and what to do if nothing/different var... – iAmOren Jul 16 '20 at 19:06
  • [`document.getElementsByName("myProduct")[0]`](https://stackoverflow.com/questions/54952088/how-to-modify-style-to-html-elements-styled-externally-with-css-using-js/54952474#54952474) is a very bad idea. – Scott Marcus Jul 16 '20 at 19:07
  • @ScottMarcus, I know - it's better to use `id` instead of `name` - just went with the data provided. Your answer, with `var urlParams = new URLSearchParams(window.location.search); let queryString = urlParams.get('selectedProduct');` is very good! – iAmOren Jul 16 '20 at 19:10
  • @ScottMarcus, that's why I didn't write that as an answer... – iAmOren Jul 16 '20 at 19:10
  • @iAmOren Actually, it's better not to use ID at all as ID's make code brittle and don't scale. With the code provided, you could/should use `.querySelector()` (as I indicate in my link). – Scott Marcus Jul 16 '20 at 19:11
  • @ScottMarcus, querySelectors are kinda new to me - thanks. I didn't realize you provided a link... Anyways, it's not what I've suggested and it's not what you wrote - it's about `getElementsByClassName()`. I wrote about `document.getElementsByName()`. Also, I think it's an opinion. I like using `id`s. – iAmOren Jul 16 '20 at 19:22
  • @iAmOren If you read my link, you'll see that `getElementsbyName()` presents the same problem as `getElementsByClassName()` (I specifically say that in the post). Those are 20+ year old API's that shouldn't be used. `.querySelector()` and `.querySelctorAll()` have been around for years and there are very real reasons to use them. – Scott Marcus Jul 16 '20 at 19:53

2 Answers2

3

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>
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
  • Thanks for the help, but perhaps I wasn't clear. I don't want to react to a change of the item. I want the passed in item selected on page load. Your second code snippet shows how to load the passed in param, which is good. The part I'm missing is how to set the selected value. Thanks again! – AndySummers2020 Jul 16 '20 at 18:51
  • @AndySummers2020 I don't understand. My first snippet is showing how to redirect with the `select` value as the querystring parameter. – Scott Marcus Jul 16 '20 at 18:52
  • Thanks again for the help. But it looks like you're showing me how to get the page to redirect when the user selects a new value in the selector. That's not what I need. What I need is, when the user browses to the URL `/mypage.html?selectedProduct=CCC`, I want `CCC` to be the selected item in the widget. Thanks again. – AndySummers2020 Jul 16 '20 at 19:01
  • @AndySummers2020 Ah, ok. That wasn't clear. I'll update to show that. – Scott Marcus Jul 16 '20 at 19:03
  • Thanks again ... just FYI I managed to assemble a solution of my own finally ... I'll post it too. – AndySummers2020 Jul 16 '20 at 19:06
  • Note to @AndySummers2020: in this good answer, you must use `id` instead of `name` and in the search part, you must use same capitalization as in options' values: `/mypage.html?selectedProduct=ccc` – iAmOren Jul 16 '20 at 19:18
0

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>
AndySummers2020
  • 411
  • 1
  • 6
  • 14