Go to a new page on select dropdown value

I have a little drop down in my nav that I wont to be able to let the user navigate to new pages.

The code looks like this but its not reading the values, only refreshing the actual page its on.


<script language="javascript">
function myChangeHandler() {
window.open(this.options[this.selectedIndex].value, '_parent');
this.form.submit(); }
</script>


<form id="formElement" method="get" action="#">
<select onchange="myChangeHandler.apply(this)">
<option></option>
<option value="/tEstablishment.php">View Site 1</option>
<option value="/currency.php">View Site 2</option>
<option value="/country.php">View Site 3</option>
</select>
</form>

You script works as soon as you stop using inline HTML event attributes to assign the event. Those inline event attributes fail to pass the context (accessed with the this keyword).
See early event handlers for more details on the problems with inline event handlers.

To fix this, and assuming that your script is at the bottom of the page where it belongs, just before the </body> tag - you can replace the inline event attribute with one that’s done via scripting instead, results in a working solution.

This is easily achieved by giving the select element a name, so that you can easily access it from the script, and then assigning the event to the select element.


<select name="viewsite">
    ...
</select>


function myChangeHandler() {         
    window.open(this.options[this.selectedIndex].value, '_parent');         
    this.form.submit();
} 

var form = document.getElementById('formElement');
form.elements.viewsite.onchange = myChangeHandler;

Oh and by the way, using language=“javascript” is incredibly obsolete. You should be using type=“text/javascript” as the scripting attribute there instead, or in modern web browsers using no attribute at all.