For instance if I have a page with two options and I click option on option two. I want to create a new url where option 2 has already been selected.
<select>
<option>Opttion 1</option>
<option >Option 2</option>
</select>
To keep it simple you can use URL Search params for that. URL Search Params can for example look like this yourlocation.com/?param1=value
param1, in that case, will be your parameter and value is its value.
You can read the param value through javascript like so:
let params = new URL(document.location).searchParams;
let selectedOption = params.get("option");
console.log(selectedOption);
For your example you can change the HTML Code like so:
<select>
<option id="option1">Option 1</option>
<option id="option2">Option 2</option>
</select>
and add some javascript:
let params = new URL(document.location).searchParams;
let selectedOption = params.get("option");
document
.getElementById("option" + selectedOption)
.setAttribute("selected", true);
This code will set the selected Option to the one in the search query.
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.