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.
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 :)
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 )
{
}
How to prevent a token created with OAuth 2.0 from expiring?
Question: [nnn]How do I make the email field and submit button disappear after an email is submitted?.
How can i go round wrapping a given string separated with commas in jquery with quotes.