Search code examples
javascriptjqueryurl-parametersdynamic-content

Show <div> when a specific URL Parameter is met


I have a form in Google Sheets, which passes URL parameters to a page, which then should show content based on the URL parameters.

So if a person checks "item 1" and "item 2" in the Google Sheet, the parameter gets passed on as follows:

https://my-url.com/?item1=value1&item2=value2

Now there's several div containers, which are set to display:none with css. When the URL parameter is met, the hidden div container should show up. So the html is:

<div class="hidden" id="value1">This content should show, when the URL parameter value 1 is passed</div>
<div class="hidden" id="value2">This content should show, when the URL parameter value 2 is passed</div>

I've found some code online, which does pretty much that, but it can only display one div at a time: https://jennamolby.com/how-to-display-dynamic-content-on-a-page-using-url-parameters/

My problem is, that for every passed parameter, a field has to show.

Can anyone help me with this? I'm really not an expert in js by any means.


Solution

  • Good Luck

    function getParameterByName(name, url = window.location.href) {
        name = name.replace(/[\[\]]/g, '\\$&');
        var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
            results = regex.exec(url);
        if (!results) return null;
        if (!results[2]) return '';
        return decodeURIComponent(results[2].replace(/\+/g, ' '));
    }
    
    var item1 = getParameterByName('item1');
    var item2 = getParameterByName('item2');
    
    if (item1 == "value1")
    {
      document.getElementById("value1").style.display = "block";
    }
    if (item2 == "value2")
    {
      document.getElementById("value2").style.display = "block";
    }
    .hidden
    {
      display: none;
    }
    <div class="hidden" id="value1">This content should show, when the URL parameter value 1 is passed</div>
    <div class="hidden" id="value2">This content should show, when the URL parameter value 2 is passed</div>