user1562023
user1562023

Reputation: 15

How to sort list items dynamically in jquery?

My question is very similar to a number of others I've found on Stack Overflow, but not quite the same.

I'v simple list as below:

<div id="preview" style="border: 1px solid #000;">

    <ul>
        <li style="list-style: none; display: none;" id="list1" class="ui-state-default">
            <input type="radio" name="answer" id="answer1" value="a" />
            <label for="answer1" id="displayAnswer1"></label>
        </li>

        <li style="list-style: none; display: none;" id="list2" class="ui-state-default">
            <input type="radio" name="answer" id="answer2" value="b" />
            <label for="answer2" id="displayAnswer2"></label>
        </li>

         <li style="list-style: none; display: none;" id="list3" class="ui-state-default">
            <input type="radio" name="answer" id="answer3" value="c" />
            <label for="answer3" id="displayAnswer3"></label>
        </li>
    </ul>
</div>

In variable named 'id', the value may come in random order,
For eg: first value of id may be 3, then li having list3 id must come in first position of list view, then id value may be 2, then li having list2 id must come in second position of list view, then at last id value may be 1, then li having list1 id must come in third position of list view.

I searched alot but all of them are sorted by alphabetically or other something like that value and they are not solving my problem.

Thanx !!

Upvotes: 1

Views: 1644

Answers (1)

mhusaini
mhusaini

Reputation: 1252

​var ids = [3, 1, 2];

var items = $("#preview li").remove();
$.each(ids, function(index, id) {
    $(items).filter("li[id='list" + ids[index] + "']")
        .appendTo($("#preview ul"));
});

See jsFiddle.

Upvotes: 3

Related Questions