views:

633

answers:

5

Hey Guys,

I have the following html:

HTML markup

<ul id="test">
   <li><a href="http://www.yahoo.com"&gt;yahoo&lt;/a&gt;&lt;/li&gt;
   <li><a href="http://www.google.com"&gt;Google&lt;/a&gt;&lt;/li&gt;
</ul>

And some JS code:

JQuery/JavaScript Code

$('ul#test').each(function()
{
   var select=$(document.createElement('select')).insertBefore($(this).hide());
   $('>li a', this).each(function()
   { 
 option=$(document.createElement('option')).appendTo(select).val(this.href).html($(this).html());
   });
});

This code produces a select dropdown menu, exactly what I want, but my question is how do I go to the url on select? So if I click yahoo, it brings me to yahoo.com?

Thanks for your help!

+1  A: 

Give this a try:

$('ul#test').each(function()
{
   // also give the select an id
   var select = $(document.createElement('select')).attr('id', 'myselect').insertBefore($(this).hide());

   $('>li a', this).each(function()
   { 
     option=$(document.createElement('option')).appendTo(select).val(this.href).html($(this).html());
   });
});

Now for redirecting....

$(function(){
  $('#myselect').live('change', function(){
    document.location.href = $(this).val();
  });
});

The live() method used because your select box is created dynamically in the DOM.

Sarfraz
Thanks, works perfect in firefox and opera, but not ie 6,7 or chrome?
Keith Donegan
+1  A: 

This should do it:

 $('ul#test').each(function()
    {
       var select=$(document.createElement('select')).insertBefore($(this).hide());
       $('>li a', this).each(function()
       { 
     option=$(document.createElement('option')).appendTo(select).val(this.href).html($(this).html());
     option.click(function(){window.location = $(this).val())});
       });
    });
Luis
Thanks! it wors again in frefox, but not in ie 6/7?
Keith Donegan
+1  A: 

add a change event to the creation of the select, and send user to the selected value.

var select=$(document.createElement('select')).insertBefore($(this).hide()).change(function(){
  document.location.href = $(this).val();
}); 
Yisroel
+1  A: 
$('ul#test').each(function()
{
   var select=$(document.createElement('select')).insertBefore($(this).hide());
   $('>li a', this).each(function()
   { 
 option=$(document.createElement('option')).appendTo(select).val(this.href).html($(this).html());
   });
   select.change(function(){
    //alert('url = ' + this.value );
    window.location.href = this.value;
  })
});

tested working demo on major browsers.

Reigel
You sir are a genius!
Keith Donegan
A: 
<select name="dest" class="selec" onchange='document.location.href=this.options[this.selectedIndex].value;'>
Homem Robô