1

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!

0

2 Answers 2

4

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).

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.