Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect on select option in select box

At the moment I am using this:

<select ONCHANGE="location = this.options[this.selectedIndex].value;"> 

it redirect me on the location inside of the option value. But it doesn't work as expected .. mean that if I click on the first option of the select, then onChange action not running. I was thinking about javascript, but I think you'll have some better suggestions guys. So how can I make it work if I click on each option it'll redirect me to the it's value?

like image 210
Lucas Avatar asked Sep 26 '11 22:09

Lucas


Video Answer


2 Answers

Because the first option is already selected, the change event is never fired. Add an empty value as the first one and check for empty in the location assignment.

Here's an example:

https://jsfiddle.net/bL5sq/

<select onchange="this.options[this.selectedIndex].value && (window.location = this.options[this.selectedIndex].value);">    <option value="">Select...</option>    <option value="https://google.com">Google</option>    <option value="https://yahoo.com">Yahoo</option>  </select>
like image 89
margusholland Avatar answered Oct 07 '22 04:10

margusholland


I'd strongly suggest moving away from inline JavaScript, to something like the following:

function redirect(goto){     var conf = confirm("Are you sure you want to go elswhere?");     if (conf && goto != '') {         window.location = goto;     } }  var selectEl = document.getElementById('redirectSelect');  selectEl.onchange = function(){     var goto = this.value;     redirect(goto);  }; 

JS Fiddle demo (404 linkrot victim).
JS Fiddle demo via Wayback Machine.
Forked JS Fiddle for current users.

In the mark-up in the JS Fiddle the first option has no value assigned, so clicking it shouldn't trigger the function to do anything, and since it's the default value clicking the select and then selecting that first default option won't trigger the change event anyway.

Update:
The latest example's (2017-08-09) redirect URLs required swapping out due to errors regarding mixed content between JS Fiddle and both domains, as well as both domains requiring 'sameorigin' for framed content. - Albert

like image 30
David Thomas Avatar answered Oct 07 '22 04:10

David Thomas