Link to dropdown selection item

Hey, so I have a button on one page and a form on another page with a dropdown with 3 possible selections with values ‘A’, ‘B’ and ‘C’.

I would like to link the button to the form page but also have it change the dropdown to a specific selection that being ‘B’. I’m guessing this is a job for javascript so looking for help if possible.

Any and all help is much appreciated.

You can do it with URLSearchParams like this

The button page

<a class="btn btn-primary" role="button" href="YOUR-FORM-PAGE.html?id=A">Section A</a>
<a class="btn btn-primary" role="button" href="YOUR-FORM-PAGE.html?id=B">Section B</a>
<a class="btn btn-primary" role="button" href="YOUR-FORM-PAGE.html?id=C">Section C</a>

The form page

<form>
	<select class="form-select" id="example">
		<option value="A">Selected A</option>
		<option value="B">Selected B</option>
		<option value="C">Selcted C</option>
	</select>
</form>

javascript

const select = document.querySelector('#example');
const params = new URLSearchParams(window.location.search);
if (select) {
  switch (params.get('id')) {
    case 'A':
      select.value = 'A';
      break;
    case 'B':
      select.value = 'B';
      break;
    case 'C':
      select.value = 'C';
      break;
  }
}

or you can use localStorage if you don’t want searchParams in the url

1 Like

Thank you kuligaposten, I’d been searching for ages to find something and thought I’d give the BS forum a go as I’m using it for this particular job.

Anyway, thanks again you’re a star :wink:

Kirby

1 Like