最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Insert new list sorted in alphabetical order, javascript or jquery - Stack Overflow

programmeradmin1浏览0评论

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
Add a ment  | 

3 Answers 3

Reset to default 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

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

发布评论

评论列表(0)

  1. 暂无评论