0

On my welcome#index page, there's a button to write a new Comment for an Article, remotely (or should I say asynchronously), using AJAX.

It works perfectly except that when an article is iterated, using rails, the browser treats the JS button as the same button throughout all iterated elements (articles).

My guess is that JS iteration is required.

How does one solve this?

# welcome/index.html.haml

- @articles.each do |article|
        = link_to "Comment", new_article_comment_path(article), class: "write-button", remote: true
        = link_to "Close", root_path, class: "close-button", remote: true
        = link_to "Commented", root_path, class: "written-button", remote: true
        #comment-form{ :style => "display:none;" }

#comments/new.js.erb

$( '#comment-form' ).html('<%= j render ("form") %>');
$( '#comment-form' ).slideDown( "slow ");
$( '.write-button' ).hide();
$( '.close-button' ).show();

#comments/create.js.erb

$( '#comment-form' ).slideUp(350);
$( '.close-button' ).hide();
$( '.written-button' ).show();

#welcome.js

//slide up and return
$( '.close-button' ).hide();
$( '.close-button' ).on('click', function() {
    $( '#comment-form' ).slideUp(350);
    $( '.close-button' ).hide();
    $( '.write-button' ).show();
});
5
  • 1
    What do you mean by the browser treats the JS button as the same button throughout all iterated elements (articles).? Commented Feb 2, 2016 at 15:33
  • For example, the AJAX works perfectly for the first article iterated but then when a user clicks the write-a-comment button for the second article iterated, it would treat the second JS button the same as the first and open the form in the first article. Commented Feb 2, 2016 at 15:36
  • Can you post an image of that on what is happening currently? or a fiddle? Commented Feb 2, 2016 at 15:39
  • Ok. I got it. Writing an answer :) Commented Feb 2, 2016 at 16:06
  • Great! Much appreciated.... Commented Feb 2, 2016 at 16:20

1 Answer 1

1

If I understood correctly, you need to provide an id for the comment-form div which equals to the article.id, so that the form shows up for that respected article.

%div{:id => "comment-form-#{article.id}", :style => "display:none;"}

And change the comments/new.js.erb to below

#comments/new.js.erb

$( "#comment-form-<%= params[:article_id] %>").html('<%= j render ("form") %>');
$( "#comment-form-<%= params[:article_id] %>" ).slideDown( "slow ");
$( '.write-button' ).hide();
$( '.close-button' ).show();
Sign up to request clarification or add additional context in comments.

1 Comment

Works for the form! How do I take care of the buttons as well?

Your Answer

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