0

I'm having a problem in jquery, I have a form with multiple div that have multiple inputs and repeats themself when i click on add button, the problem is the inputs that repeats have names in format <input name="brand_meta[designer][1][name]" type="text" class="form-control" value="">

when I press on add button I want them to repeat itself with new name brand_meta[designer][2][name]

my fiddle is here http://jsfiddle.net/prayaspanchuri/b2wskq1w/

Thanks

3
  • Why would you want to name your fields that way? There is an easier way to name fields whose data you want to send in an array or serialize: name="brand_meta[]". Otherwise, you will have to use REGEX to update the count yourself. Commented Aug 25, 2014 at 19:48
  • 2
    Why don't you use band_meta[designer][]? Most server languages will automatically convert these into an array. Commented Aug 25, 2014 at 19:48
  • Actully these are going to be added to wordpress post meta, and to fecht them in more descriptive way, I'm saving it this way, you can see the example here link Commented Aug 25, 2014 at 19:51

3 Answers 3

1

DEMO

$(document).ready(function(){
    $('.btn.btn-default.btn-sm').bind('click',function(){
        var id = $(this).attr('id');
        var n = +$('.'+id).length + 1;
        var html = $('.'+id).html()
        .replace(/\[\d+\]/g, '[' + n + ']');
        $( '.'+id+':last' ).after( $( '<div class="col-md-12"><hr style="border-top:1px #000 solid"></div><div class="'+id+'">'+html+'</div>' ) ).fadeIn('slow');
    });
});
Sign up to request clarification or add additional context in comments.

1 Comment

Great! Glad this helped. Enjoy, and checkmark the answer when you get a chance.
1
    $( '.'+id+':last' ).find('input').each(function(){
        var elemName = $(this).attr("name");
        var oldNameNum = parseInt(elemName.match(/\[(\d+)\]/)[1], 10);
        var newName = $(this).attr("name").replace(/\[(\d+)\]/, "["+(oldNameNum+1)+"]");
        $(this).attr("name", newName);
    });

DEMO: http://jsfiddle.net/b2wskq1w/2/

Comments

0

Why do you want different names? You can use names arrray like city[] which will have all input data. But if you want different name you can use an hidden input to track the name of next fields like this

 <input type='hidden' name='counter' id='counter' value='1'>

and when duplicating inputs increase its value by 1 and assign its value to input name

like this

 $("#addbtn").click(function(e){
   var countertrack= $("#counter").val();
   var newname= parseInt(countertrack+1);
   /* then assign the name using this variable*/

 })

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.