4

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!

PHP Noob
  • 1,597
  • 3
  • 24
  • 34
  • iterate over every element and when you find the correct position to insert, you can use `.insertBefore` – Amit Jul 16 '12 at 17:45

3 Answers3

4
function 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

adeneo
  • 312,895
  • 29
  • 395
  • 388
2

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.

Community
  • 1
  • 1
Zuul
  • 16,217
  • 6
  • 61
  • 88
1

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

thecodeparadox
  • 86,271
  • 21
  • 138
  • 164