Reputation: 107
I had a model with some nested attributes and needed to add new items via Javascript. This is what I came up with:
$('.add_task').click(function() {
var last_item = $('#tasks li:last');
last_item.after('<li>'+last_item.html().replace(/\d+(?=\_)|\d+(?=\])/g, function(match) {return parseInt(match)+1;})+'</li>');
});
It does the job just fine, but was wondering if anyone has a better suggestion.
Cheers!
Upvotes: 1
Views: 3099
Reputation: 107
I just put together a more generic function:
function add_new_item(element) {
var e = $(element);
var tag = e.get(0).tagName.toLowerCase();
e.after(
$('<'+tag+'>'+'</'+tag+'>').append(e.html().replace(/\d+(?=\_)|\d+(?=\])/g, function(match) {return parseInt(match)+1;}))
);
}
Upvotes: 0
Reputation: 5403
Check out Ryan Bates' complex-form-examples repo on GitHub -- he has a few options in different branches and even an unobtrusive version using JQuery (my favorite).
Upvotes: 4