user4513271
user4513271

Reputation:

Set selected option based on URL hash with Javascript

<select id="mySelect">
    <option>Apple</option>
    <option>Orange</option>
    <option>Pineapple</option>
    <option>Banana</option>
</select>

<button onclick="myFunction()">Try it</button>

<script>
    function myFunction() {
        document.getElementById("mySelect").options.selectedIndex = "2";
    }
</script>

This script selects "Pineapple" when the button is clicked. I want to do this exact same thing, except it should be selected immediately on refresh. ALSO, rather than using the selectedIndex, I would like to set the selected option based on the URL hash.

So: myname.com/#this

if location.hash == 'this' then set the option with an equal value as selected.

If it's checking for the location.hash, then I shouldn't need to use onload because it will pull the information from the url automatically. I know this is simple, I just don't know JavaScript well enough to get it put together myself.

Upvotes: 1

Views: 3388

Answers (1)

adeneo
adeneo

Reputation: 318302

You'd generally just listen to the hashchange event

window.addEventListener('hashchange', fn, false);

window.onload = fn; // fire on pageload

function fn() {
    document.getElementById('mySelect').value = window.location.hash.replace('#','');
}

Upvotes: 2

Related Questions