-2

I have the following dropdown based on bootstrap.

<div class="form-group">
  <label for="form_name">Title</label>
  <select id="hpsel" class="c-form-profession form-control">
    <option value="con01">Option 1</option>
    <option value="con02">Option 2</option>
    <option value="con03">Option 3</option>
    <option value="con04">Option 4</option>
  </select>
</div>

I want to change selected value from query string so ?something=con02 opens the page with con02 pre-selected.

I tried a few ways from other answers but they don't seem to work on my bootstrap dropdown.

2
  • 3
    can you post what you tried ? or links to those answers and how they failed to do what you want? Commented Feb 27, 2019 at 9:05
  • Tried this mainly: stackoverflow.com/questions/35181403/… Commented Feb 27, 2019 at 9:07

2 Answers 2

3

you can try this:

const urlParams = new URLSearchParams(window.location.search);
const something = urlParams.get('something');

document.getElementById('hpsel').value = something;
Sign up to request clarification or add additional context in comments.

Comments

1

You can probably do something like this:

const urlParams = new URLSearchParams(window.location.search);
const myParam = urlParams.get('something');

document.querySelector('option[value=' + myParam + ']').setAttribute('selected', "")

1 Comment

Bonus tip: you can let the browser select the matching <option> automagically, if you set the value of the <select> element to a value that matches any of the <option> elements' value.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.