pwaring pwaring - 13 days ago 5
jQuery Question

Re-numbering text input array indices with jQuery

I have the following block of HTML which is used to collect information about an item from the user as part of a form:

<div class="clone_block">
Name: <input type="text" name="items[0][name]" /><br />
Amount: <input type="text" name="items[0][amount]" /><br />
<button class="delete">Delete</button>
</div>


I can clone this element (if the user wants to add another item) and place it after the last instance of
div.clone_block
in the DOM and everything works fine, and I can also delete elements. However, I end up with multiple instances of text inputs with the same name, which means only the last one shows up in a POST request (the previous ones are overwritten). What I want to do is re-number all the items so that the first is
item[0]
, the second is
item[1]
etc.

Is there a way to do this in jQuery? Creating the names in this way makes it easier to process the POST data with PHP, so I don't want to change the naming scheme if possible.

Answer

You can implement something like this to rename the elements after each clone/removal:

function renumber_blocks() {
    $(".clone_block").each(function(index) {
        var prefix = "items[" + index + "]";
        $(this).find("input").each(function() {
           this.name = this.name.replace(/items\[\d+\]/, prefix);   
        });
    });
}

Demo: http://jsfiddle.net/Wzzf2/1/

Comments