1

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?

1
  • $('ul').children('li').length if it's greater than 0 a li is already present, at least I think. If it's correct you could also set a Boolean to avoid to check the Dom each time Commented Oct 18, 2013 at 7:37

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

4 Comments

will this be hard to be load from db or save to db? I've to retrieve everything include its position from db, what is the challenge? or just insert them 1 by 1 like normal and then sort them using sql query?
how do you want to show it. do you want to show level 1, 2 and 3in order?
are you going to give separate label for each li? store it like this. If you are going to give label for each li structre like this. {1: [label, label], 2: [label, label], 3: [label, label]}. 1, 2, 3 are representing levels.
I found it got a problem, what I want is not just they grouped together, I try the code with level 3 appended 1st, later i choose level 1, the level 1 is on the top of level 3..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.