userden
userden

Reputation: 1693

How to edit list item on click? Using AJAX, jQuery, Rails4

Currently I can edit a list item by clicking the 'Edit' link.

But, I would like to be able to just click the list item to edit it.

Here is my _item.html.erb partial. One project has many items, that's why I'm using the id="<%= dom_id(item):

<li class="klikkaa" id="<%= dom_id(item) %>">
    <%= item.description %>
    <%= link_to 'Edit', edit_project_item_path(item.project, item), remote: true %>
</li>  

Edit.js.erb:

$('#<%= dom_id(@item)%>').html("<%= j (render 'editform') %>");

I tried to do the following in assets/javascripts/item.js:

 $(document).ready(function(){
       $('.klikkaa').click(function(){
          $('#<%= dom_id(@item)%>').html("<%= j (render 'editform') %>");
       });
 });

However, I get an error on the console:

"Uncaught Error: Syntax error, unrecognized expression: #<%= dom_id(@item)%>"

How could I edit the list item when clicking the item itself, rather than clicking the 'edit' link?

Upvotes: 0

Views: 382

Answers (2)

userden
userden

Reputation: 1693

I was actually able to use the "best in place" gem after all, even though initially I thought I couldn't for a nested resource. Silly me. I just had to define the :path, e.g.:

<%= best_in_place item, :description, :path=> item_project_path(...) %>

Upvotes: 0

Yan Foto
Yan Foto

Reputation: 11388

If you want to have variables and values from rails inside your JS you are ought to change the name of your js file to item.js.erb.

An example from the Rails guide which shows how to use a rails helper (asset_path)

If you add an erb extension to a JavaScript asset, making it something such as application.js.erb, you can then use the asset_path helper in your JavaScript code:

$('#logo').attr({ src: "<%= asset_path('logo.png') %>" });

Upvotes: 1

Related Questions