samedi 27 décembre 2014

When cloning an item, is it possible to change ALL the inputs attributes and IDs as this;


Codepen link to see in action


Suppose I have this markup:



<div class="wrapper-1">
<input id="name-1" class="name-input" type="text" name="name"/>
<input id="surname-1" type="text" name="surnamename"/>
<input id="telephone-1" type="text" name="telephone"/>
<input id="email-1" type="text" name="email"/>
<input id="comments-1" type="text" name="comments"/>
</div>

<button>Clone me</button>


And this JavaScript to handle the cloning



$('button').click(function() {
var d = $('div');
var counter = d.length;
var newCounter = new Number(counter + 1);
var cloned = $('.wrapper-' + counter).clone().attr('class', 'wrapper-' + newCounter).fadeIn('slow');

//Finding items that need to have different ID
cloned.find('.name-input').attr('id', '#name-' + newCounter);

//Cloning
$('.wrapper-' + counter).after(cloned);
});


As you can see, ID counter of the input with class.name-input changes along with the wrapper's counter.


But if I want to change the name of it, and also all the IDs and names of 4 lower inputs, I have to manually insert and duplicate the same code:


cloned.find('.name-input').attr('id', '#name-' + newCounter);


And imagine I have 25 of them.


So my question is:


Is it possible to insert something like this:


cloned.find('input').attr('id', $(this).attr('id') + '-' + newCounter);


I mean so as browser automatically would parse the names and IDs of the elements and add the the counter variable to them.


Surely in this given example $(this) will refer to the element that fired the event - button, but maybe this approach is kinda possible?





Aucun commentaire:

Enregistrer un commentaire