How to convert unordered list into nicely styled <select> dropdown using jquery?
$(function() {
$('ul.selectdropdown').each(function() {
var $select = $('<select />');
$(this).find('a').each(function() {
var $option = $('<option />');
$option.attr('value', $(this).attr('href')).html($(this).html());
$select.append($option);
});
$(this).replaceWith($select);
});
});
EDIT
As with any jQuery code you want to run on page load, you have to wrap it inside $(document).ready(function() { ... });
block, or inside it's shorter version $(function() { ... });
. I updated the function to show this.
EDIT
There was a bug in my code also, tried to take href from the li element.
$('ul.selectdropdown').each(function() {
var select = $(document.createElement('select')).insertBefore($(this).hide());
$('>li a', this).each(function() {
var a = $(this).click(function() {
if ($(this).attr('target')==='_blank') {
window.open(this.href);
}
else {
window.location.href = this.href;
}
}),
option = $(document.createElement('option')).appendTo(select).val(this.href).html($(this).html()).click(function() {
a.click();
});
});
});
In reply to your last comment, I modified it a little bit but haven't tested it. Let me know.
$('ul.selectdropdown').each(function() {
var list = $(this), select = $(document.createElement('select')).insertBefore($(this).hide());
$('>li a', this).each(function() {
var target = $(this).attr('target'),
option = $(document.createElement('option'))
.appendTo(select)
.val(this.href)
.html($(this).html())
.click(function(){
if(target==='_blank') {
window.open($(this).val());
}
else {
window.location.href = $(this).val();
}
});
});
list.remove();
});