Ricki Vandenbroek
Ricki Vandenbroek

Reputation: 391

dynamic list sorting without using sort array

I was thinking of some sort algorithm to perform dynamic array sorting list, but this http://jsfiddle.net/Hms7Y/1/ seem able to solve my problem with cleaner code. But there's still few steps left to be done.

$(document).ready(function() {
  $('button').click(function() {
    var lvl = $('select').val();
    var ref = $('li.level' + lvl).last();
    $('<li class="level" '+ lvl + '>' + lvl + ' </li>').insertAfter(ref);
  });
});

what if initially I don't have any HTML markup, what is in my head now is use 3 if statement to check whether it's the 1st li when the user insert a li. is there any other better ways?

Upvotes: 1

Views: 234

Answers (1)

Sathya
Sathya

Reputation: 5308

try this jsFiddle

$(document).ready(function() {
  $('button').click(function() {
    var lvl = $('select').val();
    var ref = $('li.level' + lvl).last();
    var newLi =  $('<li class="level'+ lvl + '">' + lvl + ' </li>');

    (ref.length > 0) ? newLi.insertAfter(ref) : $("ul").append(newLi);
  });
});

Or like this jsFiddle

(ref.length > 0) ? ref.after(newLi) : $("ul").append(newLi);

Upvotes: 1

Related Questions