I'm looking for a way to append elements with javascript using javascript. Basically I have two lists of items. One has a list of items with an "ADD" button (using "link_to_remote") and the other has a list of items with a "REMOVE" button (using "link_to_remote"). When I click the "ADD" it immediately places the item into the other list. However, I need to be able to have the newly inserted item perform the reverse action for "REMOVE".
I see no way (besides, perhaps creating a partial to render a non-object) to dynamically generate dynamic items of this nature.
Have you checked out jQuery? It is a popular JavaScript library. It can do exactly what you described with ease. I've used it for years and it's never let me down.
This page of the documentation shows the append()
method. You can do stuff like...
$("span").appendTo("#foo");
The $("span")
part is finding an element (or elements) of the DOM, then the appendTo("#foo")
part is appending it to another element of the DOM.
You can also append arbitrary snippets of HTML. If needed, such a snippet could be retrieved via an AJAX request. jQuery has really simple and reliable AJAX support.
With jQuery, the basic concept is that you bind JavaScript methods to DOM elements in a separate .js
file, rather than using HTML "on_this
" or "on_that
" attibutes. So if you used jQuery for this situation, you wouldn't think in terms of generating JS code through templates. The add()
and remove()
functions would be in your .js
file ready to go and you would bind and unbind them to DOM elements as needed. For example, when you added an li
to the list, you'd unbind your add()
function from the li
and bind the remove()
function to it.