views:

487

answers:

4

What is the best way to change your URL through an html select?

<select>
<option selected="selected">Change to URL X</option>
<option>Change to URL Y</option>
</select>

What Javascript should be used?

+3  A: 

http://www.cs.tut.fi/~jkorpela/forms/navmenu.html has a good guide (which includes some good reasons why you shouldn't do this).

David Dorward
A: 

adding for example something like that in the header

<script language="JavaScript" type="text/javascript">
function jumpMenu(targ,selObj,restore){ 
  eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
}
</script>

and your select box looks then like this

<select onchange="jumpMenu('parent',this)>
<option selected="selected">Change to URL X</option>
<option value="http://www.example.com"&gt;Change to URL Y</option>
</select>
coder62
-1. Don't use `eval()`. It isn't necessary here and it is really bad practice. http://blogs.msdn.com/ericlippert/archive/2003/11/01/53329.aspx ... http://www.jslint.com/lint.html and others
Grant Wagner
+1  A: 
<script type="text/javascript">
function navigateTo(sel, target, newWindow) {
    var url = sel.options[sel.selectedIndex].value;
    if (newWindow) {
        window.open(url, target, '--- attributes here, see below ---');
    } else {
        window[target].location.href = url;
    }
}
</script>

<select onchange="navigateTo(this, 'window', false);">
<option selected="selected" value="http://www.example.com/#X"&gt;Change to URL X</option>
<option value="http://www.example.com/#Y"&gt;Change to URL Y</option>
</select>

Some useful values of target might be 'window' (the current window) or 'top' (to break out of a frameset or iframe). If you want to open a new window instead, you could use navigateTo(this, 'someWindow', true);

The value of '--- attributes ---' is set using various properties as documented here for Mozilla and here for IE. For example:

'height=300,width=400,top=100,left=100,statusbar=0,toolbar=1'
Grant Wagner
A: 

If you have jQuery you could do...

javascript:

$('#select_url').change(function(evnt){ location.href = $(this).val(); });

html:

...

Stephen