javascriptformstwitter-bootstrapnav

redirect to form and select option only on button click - else default to the standard display of nav-tab


I have a form on one nav-tab and I am linking to it from another nav-tab. I link to all of my nav-tabs from several pages using the code below.

     const hash=window.location.hash;
        const bsTab = new bootstrap.Tab(hash);
        bsTab.show();

it works, but:

  1. I would like to remove the hashtag after redirecting from the url if possible. That's one issue I'm having with this portion of my javascript.

  2. The Other is: In order to link to my form using a button, I came up with the following solution:

        function redirectToForm() {
            window.location.href = "http://www.example.com/#nav- 
        contact-me-tab";
            localStorage.setItem("selectedOption", "2");
        }
    
        const hash=window.location.hash;
        const bsTab = new bootstrap.Tab(hash);
        bsTab.show();
    
        var selectedOption = 
      localStorage.getItem("selectedOption");
        document.getElementById("reason").value = selectedOption;
        localStorage.removeItem("selectedOption");
    

This works at first glance, however, if I end up linking back to the form, the default option is no longer selected. In some cases, no option is selected. I want to always have the form show the default selected option ("0" by default which is disabled otherwise) unless my button is clicked. Only if my button is clicked do I want to change this value to option 2. If i redirect to my form from another link, I want the default disable value to display

This is my button:

<button id="gotoformselect2" onclick="redirectToForm()">Request References</button>

Maybe someone who knows javascript a little better can:

  1. help me remove the hash after redirecting to each nav-tab &
  2. can better structure my code to only select option 2 if my button is clicked.

Otherwise, if I link to the form, or any other nav-tab for that matter, I want to only use this code:

const hash=window.location.hash;
        const bsTab = new bootstrap.Tab(hash);
        bsTab.show();

Let me know if you can help! Thanks in advance.


Solution

    1. Use history API to replace the hash.
    2. Use selectedIndex to select for dropdown option.
    function redirectToForm() {
      window.location.href = "http://www.example.com/#nav-contact-me-tab";
      localStorage.setItem("selectedOption", "2");
    }
    
    if (location.hash) {
      const hash = location.hash;
      const bsTab = new bootstrap.Tab(hash);
      bsTab.show();
      history.replaceState('', null, location.origin+location.pathname); //replaces the hash
    }
    
    if (localStorage.getItem('selectedOption')) {
      const option = localStorage.getItem('selectedOption');
      document.getElementById('reason').selectedIndex = option;
      localStorage.removeItem("selectedOption");
    }