简体   繁体   中英

Auto pre-select dropdown value from URL address

I'm using the dropdown select menu which redirects users to selected cities. I have searched for this topic everywhere and tried many solutions found on stackoverflow but each of them did not work. In many cases it even disabled the redirection of my dropdown. So I am posting a new question. Hopefully that someone could solve my problem.

Problem: When I visit URL I see select delivery city - non value option. It should show the selected city based on URL address.

My URL looks like this /kategoria-produktu/CITY U SELECT (/kategoria-produktu/cadca/)

To sum up: When u visit url /kategoria-produktu/cadca the dropdown should be preselect on current url and display Čadca.

Any ideas how could I solve this? Thank you very much!

CODE

JS

if(location.href.indexOf(localStorage.country) == -1){
location.href = localStorage.country
}

function formChanged(form) {
var val = form.options[form.selectedIndex].value;
if (val !== 'non-value') {
if (localStorage) {
localStorage.country = val;
}

if (!location.href.indexOf(val)) {    
location = val;
   }
  }
 }

HTML

 <form name="form1">
 <select id="saleTerm" onchange="formChanged(this); location = 
 this.options[this.selectedIndex].value;" NAME="country" SIZE="1">
 <OPTION VALUE="non-value">Select delivery city</option>
 <OPTION VALUE="/kategoria-produktu/cadca/">Čadca</option>
 <OPTION VALUE="/kategoria-produktu/brno/">Brno</option>
 <OPTION id="bratislava" VALUE="/kategoria-produktu/bratislava/">Bratislava</option>
 </select>
 </form>

So a bunch of little things need to change here for you to get what you want. I'll try to write them all down:

  1. You should access localStorage using getItem and setItem like in the localStorage MDN documentation

  2. Use an event listener instead of the inline onchange attribute, it's much cleaner.

  3. You probably want to use includes instead of indexOf since you are looking for a substring (country) in a string (href), indexOf won't do this for you.

  4. I used location.pathname since you really only care about the path, there are better ways to get the exact path parameter you want.

  5. No need to use a <form/> as far as I can see from the code you shared.

  6. I removed /kategoria-produktu/ from the option's value attribute since its repetitive and just placed it once in the js

  7. You should change the value of the select to the city you want as the default selected. You can do this by parsing out the city from the path and setting it as the value attribute on the select

I think that's it, here is an example using those points above.

 const PREFIX = "kategoria-produktu"; window.addEventListener('load', function() { let countryInStorage = localStorage.getItem("country"); if (countryInStorage && !location.pathname.includes(countryInStorage)) { location.href = `/${PREFIX}/${countryInStorage}`; } document.getElementById("saleTerm").addEventListener("change", formChanged); setDefaultOption(); }) function setDefaultOption() { let countryPath = location.pathname.split("/")[2]; if (countryPath) { document.getElementById("saleTerm").value = countryPath; } } function formChanged() { let selectedCountry = this.value; if (selectedCountry !== "non-value") { if (localStorage) { localStorage.setItem("country", selectedCountry); } if (!location.pathname.includes(selectedCountry)) { location.href = `/${PREFIX}/${selectedCountry}`; } } }
 <select id="saleTerm" name="country"> <option value="non-value">Select delivery city</option> <option value="cadca">Čadca</option> <option value="brno">Brno</option> <option value="bratislava">Bratislava</option> </select>

If I understand it correctly, you are looking onto showing the proper option from the select element based on the URL.

Look at the example below. It basically runs a process on page load and when the DOM is ready (hence DOMContentLoaded ) to check if an option based on URL exists in the select options and picks that. You may have to update your logic depending on the URL structure. The example below assumes your URL is always formatted like http://your.domain.com/kategoria-produktu/<city>/ .

document.addEventListener("DOMContentLoaded", function() {
  // find the option based on the URL.
  let option = document.querySelector("#saleTerm > option[value='" + location.pathname + "']");

  // assign the option value to the select element if such exists.
  if (option) {
    document.querySelector("#saleTerm").value = option.value;
  }
});

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