2

I have a list like this:

<li> <input value="1" name="bla[]" /> </li>
<li> <input value="2" name="bla[]" /> </li>
<li> <input value="3" name="bla[]" /> </li>

(always the same order)

and a array like this

array('3', '1', '2');

but the order of the values in the array can change anytime. Can the list above be sorted with jQuery based on the array order?

1
  • why don't you sort it in php?? Commented Jul 7, 2010 at 17:40

2 Answers 2

2

You can do it client-side like this, if PHP isn't an option (please do it in PHP if possible, no need for JavaScript in that case):

var arr = ['3', '1', '2'];
for(var i=0; i<arr.length; i++) {
    $("ul li input[value='" + arr[i] + "']").parent().appendTo("ul");
}​

You can see a demo here


Though if you don't actually need to sort, can't you just set those values on the inputs in a loop? This assumes the real code isn't a lot more complex than the example, like this:

var arr = ['3', '1', '2'];
$("ul li input").val(function(i) {
    return arr[i];
});​

You can try that version here

0
0

You'll want to use javascript for this, but close enough to jQuery I suppose!

You can implement the sort() method. See here: http://www.w3schools.com/jsref/jsref_sort.asp

And if you need to sort with PHP see here: http://php.net/manual/en/function.sort.php

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.