Joe Isaacson
Joe Isaacson

Reputation: 4132

How do I check the order of a UL by the list item IDs?

I have the following <ul> that is sortable using jQuery UI.

<ul id="sortable1" class='droptrue'>
    <li class="ui-state-default" id="item-3">K</li>
    <li class="ui-state-default" id="item-2">I</li>
    <li class="ui-state-default" id="item-4">E</li>
    <li class="ui-state-default" id="item-1">M</li>
</ul>

$("#sortable1").on( "sortstop", function( event, ui ) {
      check to see if the order of the ul is item-1 to item-4
} );

I want to check after a user re-arranges the order to see if the list spells MIKE, or in other words, the ul is arranged incrementally by ID from item-1 to item-4. Any thoughts? Cheers

Upvotes: 2

Views: 61

Answers (3)

j08691
j08691

Reputation: 207861

Try:

$("#sortable1").sortable({
    stop: function (e, ui) {
        if($('li', this).text()==='MIKE') alert('MIKE');
    }
});

jsFiddle example

Upvotes: 0

Barmar
Barmar

Reputation: 780724

$("#sortable1").on( "sortstop", function( event, ui ) {
    var word = '';
    $(this).children('li').each(function() {
        word += $(this).text();
    });
    if (word == "MIKE") {
        alert ("You win!");
    }
} );

Upvotes: 4

Arun P Johny
Arun P Johny

Reputation: 388316

If the item-x index is always incremental then try

$("#sortable1").on("sortstop", function (event, ui) {
    var valid = true;
    $("#sortable1 > li").each(function (i) {
        if (this.id != 'item-' + (i + 1)) {
            valid = false;
            return false;
        }
    })
    if (valid) {
        console.log(valid)
    }
});

Demo: Fiddle

Upvotes: 0

Related Questions