Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery clone and rename input fields

I have the following:

<!-- group clone //-->
<div class="section">
    <div class="parent row infoOn">
        <div class="validGroup">
            <a title="remove" class="iconClose" href="#">remove</a>
                <div class="grouping">
                    <div class="clearfix valid">
                        <label>Name<span class="iconReq">&nbsp;</span>:</label>
                        <input type="password" class="text inpButton" name="items[0].first">
                    </div>
                    <div class="clearfix">
                        <label>Email<span class="iconReq">&nbsp;</span>:</label>
                        <input type="text" class="text inpButton" name="items[0].first">
                    </div>
                </div>
            </div>
        </div>
        <div class="row addControl">
            <a href="#" class="button">Add</a>
        </div>
    </div>
    <!-- group clone //-->

and jQuery:

$(function(){
    // Control clone
    $('div.addControl a.button').click(function (e){
        e.preventDefault();
        var parent = $(this).closest('.section').find('.parent:last');
        var parentInput = parent.clone();
        parentInput.find("input").val("");
        parent.after(parentInput);
    });
    $('div.validGroup a.iconClose').live('click', function (e){
        e.preventDefault();
        if ($(this).closest('.section').find('.parent').length > 1){
            $(this).closest('div.parent').remove();
        }
    });
    reflesh();
});
  1. clicking the "Add" button removes values from input fields and clones the group (2 input fields).
  2. clicking "remove" link removes group

Question: how would I change it so that when adding OR removing a new group, input fields would be renamed to name="items[INDEX].first" and name="items[INDEX].last"

For example. when there's only one "group", input fields would have names:

  • name="items[0].first"
  • name="items[0].last"

if I add another one, the new one would have

  • name="items[1].first"
  • name="items[1].first"

and so on. When I remove the first one (one with items[0].first), the second one's input names would be modified from "items[1].first" to items[0].first.

here is what it looks like:

enter image description here

like image 567
ShaneKm Avatar asked Feb 08 '11 09:02

ShaneKm


1 Answers

I figured it out:

var size = parseInt($('.form .section .parent').size());
$('.form .section .parent').each(function(index){
    $(this).find('input.text').each(function(){
        $(this).attr("name", $(this).attr("name").replace($(this).attr("name").match(/\[[0-9]+\]/), "["+index+"]"));
    });
    if (size > 1) { $(this).find('a.iconClose').show(); }else{ $(this).find('a.iconClose').hide(); }
});
like image 68
ShaneKm Avatar answered Sep 23 '22 00:09

ShaneKm