Search code examples
javascripthtmlparametershide

I want to hide a ID when specific parameter is in URL (Javascript)


I want to hide an ID named #ko when a specific parameter is found in the url.

---Example---

For example this is the thank you page when a customer send a question:

https://website.nl/bedankt?k=Vraag&n1=Your%20Name&n2=&n3=

I want to hide id="ko" when k=Vraag is in the URL

But when the a customer asked for a quotation (k=Offerte) I want to show id="ko".

https://website.nl/bedankt?k=Offerte&n1=Your%20Name&n2=&n3=

This is the html:

<span style="color: #ffffff;">Ik heb je bericht in goede orde ontvangen en zal binnen 48 uur een reactie geven op je <span class="keuze">[get_param param="k"]</span><span id="ko"> aanvraag</span>.</span>

This is what I got right now, but it doesn't seem to work.

$(document).ready(function () {
   if (window.location.href.indexOf("k=Vraag") != -1) {
      $("#ko").hide();
   }
});

Solution

  • Your code should work assuming jQuery is loaded (it was not) but I suggest you use searchParams and a toggle

    $(function() {
      const url = new URL(window.location.href);
      const keuze = url.searchParams.get("k");
      $(".keuze").toggle(keuze === "" || keuze === "Vraag");
      $("#ko").toggle(keuze !== "Vraag" && keuze !== "Offerte");
    });
    

    Plain JS

    window.addEventListener("load",function() {
      const url = new URL(window.location.href);
      const keuze = url.searchParams.get("k");
      document.querySelector(".keuze").hidden = keuze && keuze !== "Vraag";
      document.getElementById("ko").hidden = keuze === "Vraag" || keuze === "Offerte";
    });
    

    My second code after running the active code in the console shows

    enter image description here