Clone div and increment number in the name attribute

Clone div and increment number in the name attribute

by Colin Soderstrom

HTML

<div class="container">
<input type="radio" name="1_radio" class="some_vechicle" value="cars" /> Cars
<input type="radio" name="1_radio" class="some_vechicle" value="bikes" /> Bikes
<br />
<br />
<input type="text" name="2_text" class="some_name" value="" /> Model Name
<br />
<br />
<input type="text" name="3_text" class="some_year" value="" /> Year
<br />
<br />
<textarea name="4_area" rows="3" cols="10"  class="myArea" value=""></textarea>
<br />
<br />
<input type="radio" name="5_radio" class="some_color" value="cars" /> Blue
<input type="radio" name="5_radio" class="some_color" value="bikes" /> Red
<br />
<br />
<input type="text" name="6_text" class="some_manufacturer" value="" /> Manufacturer
<br />
<br />
<input type="button" class="btnAdd" value="Add" />
</div>

CSS

div {margin-bottom:10px;}

JavaScript

$(document).ready(function() {
// delegate the click event so that each .btnAdd can clone the container div
    $(document).on('click', '.btnAdd', function() {
// b finds the length of the input's name attribute
        var b = $('.container input[name]').length;
// c says to clone the first div with a class equal to container
// then find the name attribute
// In .attr we use function to set a new value to the name attribute.
        var c = $('.container:first').clone().find('[name]').attr('name', function(i, cur) {
// n matches the digits in the name attribute. The join method removes spaces
            var n = cur.match(/\d+/g).join('');
// s matches non-digit characters in the name attribute. join removes spaces        
            var s = cur.match(/\D+/g).join('');
// return will increment n, than add n + b, then the resulting value to s        
            return (b + ++n) + s;
// end the most recent filtering operation.      
        }).end()
// enter the clone after the last div with a class of container        
        $('.container:last').after(c);
    });
});