1

I'm trying to figure out how to reorder a ul using a textbox value.

Start with a ul....

<ul id="ItemList">
    <li> <some text>  <input id="Text1" type="text" value="1" /></li>
    <li> <some text>  <input id="Text2" type="text" value="2" /></li>
    <li> <some text>  <input id="Text3" type="text" value="3" /></li>
    <li> <some text>  <input id="Text4" type="text" value="4" /></li>
</ul>

Then if I change the value of Text4 from 4 to 2 the list will reorder itself while changing the value of text2 & 3 to 3 & 4 respectively.

I suspect I'm not the first person to have to do this, so if there's pointers available.

I'm not finding anything specific here, but I may not be searching right.

3
  • 2
    And what have you tried so far? Commented Jul 19, 2013 at 18:38
  • show us some jquery you have written? Commented Jul 19, 2013 at 18:40
  • So, you want to change the text of other textboxes if you change value in one of the tb? Also, is it static list or dynamic? Commented Jul 19, 2013 at 18:40

1 Answer 1

1

Here's a quick way to do this (without error checking):

$('input').keyup(function () {
    var start = $(this).index('input');
    var target = $(this).val() - 1;
    if (target < start) $(this).parent().insertBefore($('li').eq($(this).val() - 1));
    if (target > start) $(this).parent().insertAfter($('li').eq($(this).val() - 1));
});

jsFiddle example

Note that is you want to renumber the inputs after the change, add this line to the end of the function $('input').each(function(){$(this).val($(this).index('input')+1)});

Sign up to request clarification or add additional context in comments.

3 Comments

That works well for the ordering, but he wants it to also update the values all the way up and down the chain. It'll need a second function for that (probably best run immediately after the first). Also doesn't work for copy/paste, and works oddly with two-digit numbers.
@BenBarden - Does the code in the note of my answer address your concern about the update? I'm unsure of what you'e referring to. As for copy/paste and two digit numbers, that's all minor details once the main ordering is satisfied.
Fair enough - the onkeyup kibitz is just a kibitz. Might still be better as an onchange rather than an onkeyup. Other than that, yeah - it pretty much covers it. I haven't tested and can't tell you if that works to do what it's trying to do, but it looks like you have all the moving parts you need.

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.