jQuery UI onchange each loop not working as expected

406
November 22, 2016, at 3:43 PM

What I'm trying to achieve is when the list of textareas is rearranged that the name of the textareas updates to always be ordered ascending. To demonstrate:

Original

name      content
value[0]  content0
value[1]  content1
value[2]  content2

Reordered (not necessarily in this order, just an example)

name      content
value[0]  content2
value[1]  content0
value[2]  content1

What I've written should loop through the list and update the name attributes, but sometimes it just doesn't and the other times it will get the order of the names very wrong. Here's the jQuery I'm running:

$(document).ready(function(){
    $( ".sortable" ).sortable();
    $( ".sortable" ).disableSelection();
    $( ".sortable" ).on("sortchange", function( event, ui ) {
        var $i = 0;
        $('.sortable > li').each(function(){
            $(this).children('textarea').attr( 'name', 'value[' + $i + ']' );
            $i++;
        });
    });
});

And a fiddle. Not sure what I'm doing wrong.

Answer 1

use sortstop instead of sortchange:

$(document).ready(function(){
    $( ".sortable" ).sortable();
    $( ".sortable" ).disableSelection();
    $( ".sortable" ).on("sortstop", function( event, ui ) {
        var $i = 0;
        $('.sortable > li').each(function(){
            $(this).children('textarea').attr( 'name', 'value[' + $i + ']' );
            $i++;
        });
    });
});

fiddle: https://jsfiddle.net/kz4t8ph5/2/

Also take a look at Saif's answer below :)

Answer 2

use sortupdate instead of sortchange. sortchange is triggered during sorting that's why you are getting unexpected number sequence. sortupdate will be triggered when you stopped sorting. so you will get the final position and expected sequence.

$( ".sortable" ).on("sortupdate", function( event, ui )
{
}
READ ALSO
WordPress - Hiding email field and submit button after submitting

WordPress - Hiding email field and submit button after submitting

Question: [nnn]How do I make the email field and submit button disappear after an email is submitted?.

315
wrap json data separated by commas with quotes

wrap json data separated by commas with quotes

How can i go round wrapping a given string separated with commas in jquery with quotes.

405
JS Cookie path not setting

JS Cookie path not setting

I am using the following Javascript API for setting a cookie:.

416