Rails nested attributes javascript add another
I had a model with some nested attributes and needed to a开发者_StackOverflow中文版dd 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!
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).
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;}))
);
}
精彩评论