We have following markup
<input type="checkbox" class="foo" />
<input type="checkbox" class="foo" />
<input type="checkbox" class="foo" />
At some point I inject a data-keyValuePair for each instance (each one is unique – i have several calls – example only covers one assignment) with jQuery like:
$('myMagicSelector').data('counter', '1');
Now I am trying to sort this instance with following code
var $checkboxes = $('.foo').filter('checked');
$checkboxes.sort(function (a, b) {
var dataA = a.data('counter');
var dataB = b.data('counter');
return dataA < dataB;
});
I know … this can’t work …
- How do I fix my code, without introducing neither
$(a)nor$(b)in my sort-function? - Is there any library which can do this for me (jquery-specific)?
- Any other inputs?
Very important note:
I do not want to change the ordering in my UI (nope: no UI-sort-thing… like tinySort), and the ordering in my UI does not correspond to the expected result – that’s why I need to sort on the fly, and not via the markup at creation …
You can use
el.getAttribute("data-counter")in place of$(a).data("counter")Example fiddle