mardi 24 février 2015

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.


Aucun commentaire:

Enregistrer un commentaire