1

I adding new form elements into a sortable list. When the list is rearranged, I'd the like ID's to be consecutive. Code so far:

$( "#sortable" ).sortable();
$( "#sortable" ).disableSelection(); 

var counter = 1; 

    $('a').click(function () {
    var elems = '<li>'
    '<input name="q_' + counter + '" type="text"/>' +
    '<select name="type_' + counter + '" >
           <option value="1">1</option>
           <option value="2">2</option>
           <option value="3">3</option>
     </select>' +
    '</li>' ;
    $('#sortable').append(elems);    


    counter++;    
    return false;


});

This produces a list with consecutive IDs, which go out of sync when rearranged. How can I use jquery to iterate through the list and reassign element IDs?

4

2 回答 2

4

Put the function inside the update callback

$( "#sortable" ).sortable({
    update: function(event, ui) {
      $('select').each(function(index){
         $(this).attr('id', index + 1);
      });
    }
});
于 2013-05-07T12:52:56.887 回答
1

You can use the change event for this.

$("#sortable").sortable({
   change: function(event, ui) {
      // reset all the IDs
      $.each($('select'), function(i, v) {
         this.id = "type_" + i; // or the "name" attribute?
      });
   }
});
于 2013-05-07T12:53:58.307 回答