开发者

How to open up a form for dynamic data with jquery in rails application?

I have list of books listed on the user's profile from the database,i want when i click on each book to open up a form for that particular boo开发者_如何转开发k.My idea was

book_controller

 @id=current_user.book.id

view

 <div id="<%= @id %>" >form </div>

javascript

 $('#<%= @id %>').click(function(){//show form});

I am sorry i am newbie in programming,i am not sure erb could be excuted in javascript.Any easier way will be appreciated.Thank you in advance.


Here's one way you could accomplish this.

Books controller

def show
    # could make a custom controller action too
    @book = Book.find(params[:id])
end

The partial used by the show

Book with ID <%= @book.id %>
etc

The user profile

<% current_user.books.each do |book| %>
    <div id="book_<%= b.id %>
        <%= link_to "Show Book", "#", :id => book.id, :class => "show_book" %>
    </div>
<% end %>

jQuery:

$(".show_book").click(function() {
    $.ajax({
        url: '/books/show/',
        data: {id, $(this).id}
        success: function(html){
            $("#book_" + $(this).id).empty();
            $("#book_" + $(this).id).append(html);
        }
    });
});

Please Note: I may have messed up a bit of syntax, and I apologize if I did, but the idea is there.

The idea being this: you make a div in your user profile where you can put a link called "Show Book". That div gets a unique ID based on the book id. The link gets a class called "show_book". The jQuery looks for all links with this name and gives their click action a function. Internally, that function does an AJAX call to the path you specify, sending any data you want (and it will go in to the params hash). When it's done, it will return the data to the AJAX request and you can clear the div and then throw the information in.

I hope this gets you started!

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜