Take the following code for example:
<div id="instructor_trainers">
<div id="trainer-1" class="trainer-group form-group row">
<div class="col-md-6">
<select class="form-control" id="trainers[1][trainer]" name="trainers[1][trainer]">
<option value="">-- Select --</option>
</select>
</div>
<div class="col-md-6">
<input type="text" class="trainer-expiration form-control" placeholder="Expiration" id="trainers[1][expiration]" name="trainers[1][expiration]" value="">
</div>
<div class="col-xs-12">
<textarea class="trainer-comments form-control" placeholder="Comments" id="trainers[1][comments]" name="trainers[1][comments]"></textarea>
</div>
</div>
<div id="trainer-2" class="trainer-group form-group row">
<div class="col-md-6">
<select class="form-control" id="trainers[2][trainer]" name="trainers[2][trainer]">
<option value="">-- Select --</option>
</select>
</div>
<div class="col-md-6">
<input type="text" class="trainer-expiration form-control" placeholder="Expiration" id="trainers[2][expiration]" name="trainers[2][expiration]" value="">
</div>
<div class="col-xs-12">
<textarea class="trainer-comments form-control" placeholder="Comments" id="trainers[2][comments]" name="trainers[2][comments]"></textarea>
</div>
</div>
<div id="trainer-3" class="trainer-group form-group row">
<div class="col-md-6">
<select class="form-control" id="trainers[3][trainer]" name="trainers[3][trainer]">
<option value="">-- Select --</option>
</select>
</div>
<div class="col-md-6">
<input type="text" class="trainer-expiration form-control" placeholder="Expiration" id="trainers[3][expiration]" name="trainers[3][expiration]" value="">
</div>
<div class="col-xs-12">
<textarea class="trainer-comments form-control" placeholder="Comments" id="trainers[3][comments]" name="trainers[3][comments]"></textarea>
</div>
</div>
</div>
Each trainer element inside of div instructor_trainers consists of three input fields, which are all contained inside of a trainers array. Whenever a new element is created, the index is found by incrementing the existing number of elements by one. When an element is removed, this value is decremented by one, and elements are only able to be removed in the order they were added (so if I were to click on my remove button trainer-3 would be removed, then trainer-2, and finally trainer-1).
Is there a way to update the array indexes automatically if an element is removed out of order. For example, if I changed my remove function to remove a specific id (such as trainer-2) is there a way to shift the index values of all elements after the removed element? So if trainer-2 is removed, then the three inputs in trainer-3 would have their index values shifted to 2?
This could be done by rebuilding each element after the deleted element, but it just feels like I'm missing something, like there's an easier way to go about it.