Reputation: 31
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.
Upvotes: 1
Views: 236
Reputation: 207901
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));
});
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)});
Upvotes: 1