jQuery - Sortable get order


Topic: jQuery - Sortable get order

Zhao pro asked 6 years ago

I would like to create a form with sortable elements inside. When it submits I need to get the order of elements. How can I get that in jQuery? For eg 1, 2, 3, etc and if  
<ul id="sortable" class="list-group">
  <li class="list-group-item active">Item 1</li>
  <li class="list-group-item">Item 2</li>
  <li class="list-group-item">Item 3</li>
  <li class="list-group-item">Item 4</li>
  <li class="list-group-item">Item 5</li>
  <li class="list-group-item">Item 6</li>
  <li class="list-group-item">Item 7</li>
  <li class="list-group-item">Item 8</li>
</ul

Mateusz Łubianka staff answered 5 years ago

Hi @mdeak,

To get order of sortable items you can use this code: Html:

<section>

      <div class="row">
        <div class="col-md-12">
          <ul id="sortable" class="list-group">
            <li data-id="1" class="ui-state-highlight">Item 1</li>
            <li data-id="2" class="ui-state-highlight">Item 2</li>
            <li data-id="3" class="ui-state-highlight">Item 3</li>
            <li data-id="4" class="ui-state-highlight">Item 4</li>
            <li data-id="5" class="ui-state-highlight">Item 5</li>
          </ul>
        </div>
      </div>
      <button id="get" class="btn btn-primary">Get order</button>
    </section>

Init:

$(function () {
      $("#sortable").sortable();
    });

Get sorted:

$('#get').on('click', function() {

        var idsInOrder = $("#sortable").sortable('toArray', {
      attribute: 'data-id'
    });


      console.log(idsInOrder);
    })

Best,


Jakub Strebeyko staff answered 6 years ago

Hi there Zhao,

The way I see here would be to have a custom function looking through .sortable children on submit. I am adding it as a feature request for the dev team to consider.

Best,
Kuba


mdeak pro premium priority commented 5 years ago

It would be fantastic if we could submit the reordered list as a form and then simply process the element IDs in the listed order.


Please insert min. 20 characters.

FREE CONSULTATION

Hire our experts to build a dedicated project. We'll analyze your business requirements, for free.

Status

Answered

Specification of the issue
  • User: Pro
  • Premium support: No
  • Technology: MDB jQuery
  • MDB Version: 4.5.10
  • Device: Desktop
  • Browser: Chrome
  • OS: Windows 10
  • Provided sample code: No
  • Provided link: No