Onchange open URL via select - jQuery
It is pretty simple, let's see a working example:
<select id="dynamic_select">
<option value="" selected>Pick a Website</option>
<option value="http://www.google.com">Google</option>
<option value="http://www.youtube.com">YouTube</option>
<option value="https://www.gurustop.net">GuruStop.NET</option>
</select>
<script>
$(function(){
// bind change event to select
$('#dynamic_select').on('change', function () {
var url = $(this).val(); // get selected value
if (url) { // require a URL
window.location = url; // redirect
}
return false;
});
});
</script>
$(function() {
// bind change event to select
$('#dynamic_select').on('change', function() {
var url = $(this).val(); // get selected value
if (url) { // require a URL
window.location = url; // redirect
}
return false;
});
});
<select id="dynamic_select">
<option value="" selected>Pick a Website</option>
<option value="http://www.google.com">Google</option>
<option value="http://www.youtube.com">YouTube</option>
<option value="https://www.gurustop.net">GuruStop.NET</option>
</select>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"
></script>
.
Remarks:
- The question specifies jQuery already. So, I'm keeping other alternatives out of this.
- In older versions of jQuery (< 1.7), you may want to replace
on
withbind
. - This is extracted from JavaScript tips in Meligy’s Web Developers Newsletter.
.
I think this is the simplest way:
<select onchange="if (this.value) window.location.href=this.value">
<option value="">Pick one:</option>
<option value="/foo">Foo</option>
<option value="/bar">Bar</option>
</select>