Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
4
rated 0 times [  5] [ 1]  / answers: 1 / hits: 15890  / 13 Years ago, sat, february 25, 2012, 12:00:00

I have this markup



<div class=input text>
<label for=Experience0ExperienceContent>Experience Content</label>
<input name=data[Experience][0][experience_content] class=span3 id=Experience0ExperienceContent type=text>
</div>


It's possible to clone or duplicate it incrementing the 0 value every time the user make click on a link? I mean all the 0 when user clicks one time the link need to go to 1 then if click again need to go to 2 and so on and of course maintaining the same markup every time, any advice or help?



Cheers and thanks in advance


More From » jquery

 Answers
25

You could try a little something like this:​



$(a).click(function() {        
$(div.input.text)
.last()
.clone()
.appendTo($(body))
.find(input).attr(name,function(i,oldVal) {
return oldVal.replace(/[(d+)]/,function(_,m){
return [ + (+m + 1) + ];
});
});
return false;
});


As demonstrated here: http://jsfiddle.net/6Xg4S/



Essentially on click of your anchor it will clone the last div and append it to the body (at least my example appends to the body - obviously you could append it to something more specific or .insertAfter() the last one), then take the number from the middle of the name and increment it via a regex replace.



Having done that though I'd like to note that you don't need to give your inputs unique names: all of the server-side technologies that I'd care to use can deal with multiple request parameters with the same name (e.g., Java has getParameterValues() that returns an array).



EDIT: Here's a version that clones only the input element, specifically the last input in the div, updates its id, and appends it to the end of the div. As per your comment this no longer changes the name (though obviously you can just throw in an additional .attr() call as above if you want to change the name too). Oh, and also this sets the value to blank (I forgot to do that above).



$(#extra a).click(function() {   
var $div = $(this).next();
$div.find(input)
.last()
.clone()
.appendTo($div.append(<br/>))
.val()
.attr(id,function(i,oldVal) {
return oldVal.replace(/d+/,function(m){
return (+m + 1);
});
});
return false;
});


Demo: http://jsfiddle.net/6Xg4S/4/


[#87219] Friday, February 24, 2012, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
gerardamosy

Total Points: 600
Total Questions: 116
Total Answers: 102

Location: Ukraine
Member since Tue, May 30, 2023
1 Year ago
;