1

I came across a function that does exactly what I need to do in my questionnaire, but it operates using an ID and I need to do it by name.

here's the fiddle for it https://jsfiddle.net/HGtmR/4/

    var cloneCount = 1;;
   $("button").click(function(){
      $('#id')
          .clone()
          .attr('id', 'id'+ cloneCount++)
          .insertAfter($('[id^=id]:last'))
          .text('id ' + (cloneCount-1)); //<--For DEMO
   });

Here's a fiddle to the section of my form that I'd like to apply it to https://jsfiddle.net/6djnv9u2/7/

mplungjan
  • 169,008
  • 28
  • 173
  • 236
Optiq
  • 2,835
  • 4
  • 33
  • 68

1 Answers1

1

Of course - using the attribute selector - and perhaps take the first if there are more.
NOTE: Name is not a valid attribute of a DIV - now I see you are cloning divs in your fiddle

 var cloneCount = 1;
 $("button").click(function(){
   $('input[name="name0"]').eq(0) // only that one
      .clone()
      .attr('name', 'name'+ cloneCount++)
      .insertAfter($('[name^=name]:last'))
      .text('name ' + (cloneCount-1)); //<--For DEMO
 });

If you need them to have the same name you could do

 $("button").click(function(){
   var $q = $('input[name="question"]').last();
   $q.clone().insertAfter(q);
 });
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • Dont forget to add eq(0); so next elements should not be recopied. $('input[name="somename"]:eq(0)') – Trishul Aug 27 '15 at 05:42
  • Thanks - that is why I added first(). If there is only one named name0 there should only be one copy – mplungjan Aug 27 '15 at 05:43
  • do I need to do one of these for each name I want to be changed? Or is there a way to make it collect them all and rename them? – Optiq Aug 27 '15 at 05:45
  • changing name is not necessary, name can be same – Trishul Aug 27 '15 at 05:46
  • And using ^= you can get the ones starting with something. Remove the eq(0) if you want all of them, but then the collection will grow each time you click – mplungjan Aug 27 '15 at 05:50