Reputation: 1
I want to use a form to let users rank a list of items and store the ranking in a form field called ranking. I am using "Sortable" to and "toArray" for this:
<ul id="items" class="list-group list-group-numbered" style="cursor: move">
<li data-id="1" class="list-group-item list-group-item-action">Option 1</li>
<li data-id="2" class="list-group-item list-group-item-action">Option 2</li>
<li data-id="3" class="list-group-item list-group-item-action">Option 3</li>
<li data-id="4" class="list-group-item list-group-item-action">Option 4</li>
<li data-id="5" class="list-group-item list-group-item-action">Option 5</li>
</ul>
<script src="https://cdn.jsdelivr.net/npm/sortablejs@latest/Sortable.min.js"></script>
<script>
let el = document.getElementById('items');
let sortable = Sortable.create(el, {
animation: 150,
onChange: function (evt) {
forminputs.ranking.value = sortable.toArray().join(',');
}
});
</script>
<input type="hidden" name="ranking" id="ranking">
In the data, the variable ranking mostly stores strings which contain the IDs of the items to sort. However, occasionally (about 10% in my data), it would store a string where one of the IDs appears twice, i.e., the array has length+1 compared to what I expected. The duplicate ID always appears at the end of the array, i.e., if n+1 elements appear, then the first n elements are unique, and the n+1th element is a duplicate of one of the previous elements.
I expect an array of constant length from each input. I tried to replicate it myself, but couldn't. Could it be an issue related to a specific browser? Since the duplicate is always at the end, can I potentially assume that the first n elements represent the actual ranking submitted by the user?
Upvotes: 0
Views: 42
Reputation: 687
jQuery-UI Sortable uses a placeholder element while dragging to indicate the drop insertion position. Maybe you are reading that one out, since you are using the OnChange
event to read out (the placeholder element can be identified as it carries the class ui-sortable-placeholder
). onChange
can be triggered several times while the user keeps dragging the element around.
You probably want to read out the final sequence in the onUpdate
event instead, which is triggered only once per drag-and-drop. See: https://api.jqueryui.com/sortable/#event-update
Upvotes: 0