Using Javascript To Change Url Based On Option Selected In Dropdown
I cannot seem to get this to work. Any thoughts? this is in your code, but it's not the
<select>
element. Here's some working code:<htmlxmlns="http://www.w3.org/1999/xhtml"><head><metahttp-equiv="Content-Type"content="text/html; charset=utf-8" /><title>Select Video Test</title><scripttype="text/javascript">functionselectVideo(){
var urlString = "http://www.mycookingsite.com/";
var videos = document.getElementById('videos');
var selectedVideo = videos.options[videos.selectedIndex];
if (selectedVideo.value != "nothing"){
window.location = urlString + selectedVideo.value;
}
}
</script></head><body><form><selectid='videos'onchange="selectVideo()"><optionvalue="nothing">Select video from this list</option><optionvalue="how-to-grill-burgers">How to Grill Burgers</option><optionvalue="how-to-hard-boil-eggs">How to Make Hard-Boiled Eggs</option></select></form></body></html>
Solution 2:
Your function won't run within the context of the 'select' element because you're just calling the function regularly. To combat this either unobtrusively handle the event or pass 'this' from within your 'onchange' handler:
Option 1:
// first, give 'select' an id
document.getElementById('select-id').onchange = selectVideo;
Option 2:
<select onchange="selectVideo.call(this)">
Option 3: (The best IMHO)
functionaddEvent(elem, type, fn) {
varW3C, callback = function(e){ fn.call(elem, e||window.event); };
((W3C = elem.addEventListener) || elem.attachEvent)
((W3C?'':'on') + type, callback, false);
return callback;
}
addEvent(document.getElementById('select-id'), 'change', selectVideo);
Solution 3:
You can only use this
when you are in the event code. When you are in the function, this
referrs to the window object. Send the reference as a parameter to the function:
<htmlxmlns="http://www.w3.org/1999/xhtml"><head><metahttp-equiv="Content-Type"content="text/html; charset=utf-8" /><title>Select Video Test</title><scripttype="text/javascript">functionselectVideo(obj){
var urlString = "http://www.mycookingsite.com/";
var selectedVideo = obj.options[obj.selectedIndex];
if (selectedVideo.value != "nothing"){
window.location = urlString + selectedVideo.value;
}
}
</script></head><body><form><selectonchange="selectVideo(this)"><optionvalue="nothing">Select video from this list</option><optionvalue="how-to-grill-burgers">How to Grill Burgers</option><optionvalue="how-to-hard-boil-eggs">How to Make Hard-Boiled Eggs</option></select></form></body></html>
Solution 4:
Is this homework? There are multiple ways to correct it but one simple way is to make selectVideo take a obj parameter, then change all references to inside it to obj. Then, do selectVideo(this) in the onchange.
I highly recommend QuirksMode, particularly this this page, if you want to really understand this.
Post a Comment for "Using Javascript To Change Url Based On Option Selected In Dropdown"