html - how to compose href based on selection menu

Viewed 37

How to compose web address based on selection menu?

The desired link should be composed of choosen values, for instance, "https://www.Opel_Volvo.com"

In the provided code, I need to change

  action="https://www.lipsum.com"

for a string composed of selected possibilities.

<html>
<body>
<h1>CAR</h1>
<form
  target="_blank"
  action="https://www.lipsum.com"
  method="get"
>

  <label for="car1">Choose a car 1:</label>
  <select id="car1" name="car1">
    <option value="volvo">Volvo</option>
    <option value="saab">Saab</option>
    <option value="opel">Opel</option>
    <option value="audi">Audi</option>
  </select><br><br>

  <label for="car2">Choose a car 2:</label>
  <select id="car2" name="car2">
    <option value="volvo">Volvo</option>
    <option value="saab">Saab</option>
    <option value="opel">Opel</option>
    <option value="audi">Audi</option>
  </select><br><br>


  <input type='submit' value='OK'>

</form>


</body>
</html>

After advice

enter image description here

2 Answers

You can use JavaScript to add input event listener to the select elements, and set the action attribute of form accordingly.

let sel1 = document.querySelector("#car1");
let sel2 = document.querySelector("#car2");
let form = document.querySelector("form");

[sel1, sel2].forEach(s =>{
  s.addEventListener("input", ()=>{
    let url = `https://www.${sel1.value}_${sel2.value}.com`;
    form.setAttribute("action", url)
    console.log(form.action)
  })
})
<html>
<body>
<h1>CAR</h1>
<form
  target="_blank"
  action="https://www.lipsum.com"
  method="get"
>

  <label for="car1">Choose a car 1:</label>
  <select id="car1" name="car1">
    <option value="volvo">Volvo</option>
    <option value="saab">Saab</option>
    <option value="opel">Opel</option>
    <option value="audi">Audi</option>
  </select><br><br>

  <label for="car2">Choose a car 2:</label>
  <select id="car2" name="car2">
    <option value="volvo">Volvo</option>
    <option value="saab">Saab</option>
    <option value="opel">Opel</option>
    <option value="audi">Audi</option>
  </select><br><br>

  <input type='submit' value='OK'>
</form>
</body>
</html>

There are several way to achieve this.

You could use Javascript to change the url of the form action. Something like:

<select id="car1" name="car1" onchange="document.forms[0].setAttribute('action','https://'+car1.value+'_'+car2.value+'.com'">
...

Or you could send the form data to a php script which redirects the user to the desired site.

Or you could use redirects in your .htaccess file:

Redirect 303 https://www.lipsum.com?car1=opel&car2=volvo https://www.Opel_Volvo.com
Related