Select "Menu", go to url for selection using jQuery?
I have the following html:
HTML markup
<ul id="test">
<li><a href="http://www.yahoo.com">yahoo</a></li>
<li><a href="http://www.google.com">Google</a></li>
</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 creates a dropdown menu, exactly what I want, but my question is, how can I navigate to the url when selected? So if I click on yahoo does it take me to yahoo.com?
Thanks for your help!
+2
a source to share
5 answers
$('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 in major browsers.
+7
a source to share
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 the redirect ....
$(function(){
$('#myselect').live('change', function(){
document.location.href = $(this).val();
});
});
Use the live () , because your power of choice is created dynamically in the DOM.
+1
a source to share
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())});
});
});
+1
a source to share