pwaring pwaring - 1 year ago 63
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>

I can clone this element (if the user wants to add another item) and place it after the last instance of
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
, the second is

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 Source

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() {
  =\[\d+\]/, prefix);   


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download