ab11
ab11

Reputation: 20100

JQuery, how to reorder dom elements alphabetically?

I am displaying a list of checkboxes in a modal. The modal contents looks something like:

<div class="container>
  <label>
    <input type="checkbox" name="A name" value="A Value">
    &nbsp;A Value
  </label>
  <br>
  <label>
    <input type="checkbox" name="B name" value="B Value">
    &nbsp;B Value
  </label>
  ....
<div>

The checkboxes are reorder-able. But each time the modal gets displayed, I'd like to rest the order of the checkboxes so they display in alphabetic order. Sorting them is easy enough, using the below code, but any suggestions on how I can manipulate the container so that the checkboxes are in the proper order?

var sorted = modal.find(':checkbox').sort(function(a, b) {

        var aText = a.value;
        aText = aText.trim().toLowerCase();

        var bText = b.value;
        bText = bText.trim().toLowerCase();


        if (aText < bText) {
          return -1;
        } else if (aText > bText) {
          return 1;
        } else {
          return 0;
        }
      });

Upvotes: 2

Views: 349

Answers (3)

Jaromanda X
Jaromanda X

Reputation: 1

var container = document.querySelector(".container");
sorted.forEach(function(chk) {
    var elementToMove = chk.parentElement; // move the label
    container.appendChild(elementToMove);
});

almost does it ... but those pesky < BR > spoil the deal

add

.container>label { display:block; }

to your CSS, and remove the < BR >

edit: I accidentally didn't jQuery on purpose

Upvotes: 0

Bhushan Kawadkar
Bhushan Kawadkar

Reputation: 28513

Try this : use below code to rearrange your checkboxes. (Assuming that your sort function is correct)

var sorted = modal.find(':checkbox').sort(function(a, b) {

        var aText = a.value;
        aText = aText.trim().toLowerCase();

        var bText = b.value;
        bText = bText.trim().toLowerCase();


        if (aText < bText) {
          return -1;
        } else if (aText > bText) {
          return 1;
        } else {
          return 0;
        }
      }).each(function (_, checkbox) {
              $(checkbox).closest('.container').append($(checkbox).closest('label'));
        });

JSFiddle Demo

NOTE - Please move your <br> inside <label> tag

Upvotes: 1

sroes
sroes

Reputation: 15053

First sort the labels:

var $sorted = modal.find('label:has(:checkbox)').sort(function(a, b) {
    var valA = $(a).find(':checkbox').val().trim().toLowerCase();
    var valB = $(b).find(':checkbox').val().trim().toLowerCase();
    return valA.localeCompare(valB);
});

Then add them again to the parent:

$container.empty().append($sorted.after('<br />'));

Upvotes: 1

Related Questions