Home > front end >  Change option on select input by clicking on a button
Change option on select input by clicking on a button

Time:11-23

I want to change the value on my select input by clicking on a button, but this button is on an other page.

My button is on the home page and the form with the select input is on contact page. The select input look like this :

<select name="menu-vol"  id="select-vol" aria-required="true" aria-invalid="false">
<option value="">---</option>
<option value="Le marmaille">Le marmaille</option>
<option value="Le Vol découverte">Le Vol découverte</option>
<option value="Le plus">Le plus</option>
<option value="L'infini">L'infini</option>
<option value="Le vol des Hauts">Le vol des Hauts</option>
<option value="Le vol de distance">Le vol de distance</option>
<option value="Le vol du Maïdo">Le vol du Maïdo</option>
</select>

For exemple i want when i click on the button, the input select value change to "Le Vol découverte"

I'm trying this solution but isn't work because is not a bootstrap template i think and in this exemple the form input and the button is on the same page, not like my case.

CodePudding user response:

You can achieve this in very simple step:

In home page make your button an anchor tag like below:

<a href="contact.html?param=test">Goto Contact</a>

you can see in href I've passed a param with value.

Now in contact.html page, just use this below codes:

if (window.location.search.includes('param=test')) {
  document.getElementById('select-vol').value = 'Le Vol découverte';
}

Now whenever you click the anchor button in home page it redirects to contact.html page with param=test, and in contact.html page I'm checking condition if param=test then show the selected option which I passed as value in js code.

CodePudding user response:

Well let's assume you have a link like this:

<a href="contact.html">Contact Page</a>

You can change the href in order to send query parameters to the target page like this:

<a href="contact.html?selectedValue=Le marmaille">Contact Page</a>

And finally you can get the query value from URL in the Contact page and change the selected option:

const selectedValue = (new URL(document.location)).searchParams.get("selectedValue");
document.getElementById("select-vol").value = selectedValue;

You can read more here.

  • Related