views:

90

answers:

5

I've got a dropdown that's code is as follows:

<select name="month" onchange="updateURL()">
  <option value="1">January</option>
  <option value="2">February</option>
  <option value="3">March</option>
  ...
  <option value="12">December</option>
</select>

As you can see, when it changes, it calls the javascript function: updateURL().

What code should I put in the updateURL function that would change the document's location to:

/calendar/(insert value of the selected option here)
A: 
window.location.assign(url);
ChaosPandion
A: 

Off the top of my head:

<select id="month"></select>

var monthDrop = document.getElementById('month');

monthDrop.onchange = function() {
    var value = this.value, numericRep = parseInt( value, 10 );
    if ( !isNaN(numericRep) ) {
        location.href = 'http://sitename.com/calendar/' + value;
    }
}
meder
A: 
<select onchange="javascript: location.href='/calendar/' + this.options[this.selectedIndex].value;">
...
</select>
Björn
Thanks, worked for me!
JasonV
‘javascript:’ at the front of event handlers doesn't do anything. (Actually it defines a pointless label you'll never use. It's confused with ‘javascript:’ URLs — which should actively never be used!)
bobince
right - it's implied that the onchange and other similar inline event handlers will execute javascript code. you should opt for unobtrusive javascript so you can keep behavior, styles, markup separate.
meder
A: 
<script>
function updateURL(obj) {
    window.location.assign("/calendar/" + obj.value);
    return true;
}
</script>
<select name="month" onchange="updateURL(this)">
  <option value="1">January</option>
  <option value="2">February</option>
  <option value="3">March</option>
  ...
  <option value="12">December</option>
</select>
+1  A: 

As you can see, when it changes, it calls the javascript function: updateURL().

This isn't necessarily a good idea. The select element's onchange is also fired when a keyboard user is stepping through the options with the arrow keys, so the page change makes it impossible to navigate through the keyboard, for which disabled and laptop users won't thank you.

Then when you use the ‘back’ button, the select element is in the wrong state, pointing at the page you were going to instead of the page you came from, which makes the action of changing it quite confusing (it might reload the current page, or fail to load the new page).

Also it stops browsers providing useful options like ‘open in new tab’ or ‘bookmark link’ when it's stuck behind a select box.

The select-as-navigational-tool idiom is a bit discredited today. Whilst you can certainly repair some of its flaws with more complicated scripting, you might want to consider having something like a scripted drop-down div populated with simple links instead.

bobince