开发者

Rails nested attributes javascript add another

开发者 https://www.devze.com 2022-12-14 15:00 出处:网络
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:

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;}))
  );
}
0

精彩评论

暂无评论...
验证码 换一张
取 消