I have lists, already sorted alphabetically as below:
<ul>
<li><a href='#'>Apple</a></li>
<li><a href='#'>Banana</a></li>
<li><a href='#'>Grapes</a></li>
<ul>
So i wanted to add new list which has the value of Chico
so it should be inserted between Banana
and Grapes
...like it will fade in. So i have a form or an input field to add a new list of fruits...
Is there any way to do that using jquery or javascript?
Thanks!
I have lists, already sorted alphabetically as below:
<ul>
<li><a href='#'>Apple</a></li>
<li><a href='#'>Banana</a></li>
<li><a href='#'>Grapes</a></li>
<ul>
So i wanted to add new list which has the value of Chico
so it should be inserted between Banana
and Grapes
...like it will fade in. So i have a form or an input field to add a new list of fruits...
Is there any way to do that using jquery or javascript?
Thanks!
Share Improve this question asked Jul 16, 2012 at 17:38 PHP NoobPHP Noob 1,6153 gold badges25 silver badges34 bronze badges 1-
iterate over every element and when you find the correct position to insert, you can use
.insertBefore
– Amit Commented Jul 16, 2012 at 17:45
3 Answers
Reset to default 4function sortAlpha(a,b){
return a.innerHTML.toLowerCase() > b.innerHTML.toLowerCase() ? 1 : -1;
}
$("#insert").on('click', function() {
var newLi = $("<li><a href='#'>"+$("#fruit").val()+"</a></li>").hide();
$('li', 'ul').add(newLi.fadeIn(800)).sort(sortAlpha).appendTo('ul');
});
FIDDLE
See this working Fiddle Example!
This function adds the new list item to the provided list. After adding the new item, it will sort all items by their contents.
function addNewListItem($list, $ele) {
// append new element
$list.append($ele);
// get all elements
var listItems = $list.children('li').get();
// sort elements by contents
listItems.sort(function(a, b) {
return $(a).text().toUpperCase().localeCompare($(b).text().toUpperCase());
});
$.each(listItems, function(idx, itm) { $list.append(itm); });
}
Example usage:
//Creating a new item
var $newLI = $('<li/>').append($('<a/>', {"href":'#',"title":''}).html('Chico'));
// adding and sorting
addNewListItem($('ul'), $newLI);
Original sort function is credit to Dan @ onemoretake, via this stackoverflow answer.
CSS
.hide {
display: none
}
jQuery
function addListElement(el) {
var lis = $('ul li').add(el).sort(function(a, b) {
return $('a', a).text() > $('a', b).text();
});
$('ul').html(lis).find('.hide').fadeIn(3000, function() {
$(this).removeClass('hide')
});
}
addListElement('<li class="hide"><a href="#">Chico</a></li>');
Working sample