0

I want to take the value of a js variable, and have it available in my rails view without having to refresh the page. I'm not sure if this is even the best way to go about it.

I have a varying amount of titles that can be clicked. When one is clicked, I want to grab the value of that and pass it to a div that displays info about the object clicked.

#drafts
  - @posts.all.each_with_index do |post, index|
  = link_to strip_tags(post.title), "#", id: "post#{index}"


#post-view
  .title-editor
    = post_that_was_clicked.title
  hr
  .body-editor
     = post_that_was_clicked.body

js:

$('#drafts').click(function(e) {
  var txt = $(e.target).text();
  alert(txt);
});

How can I accomplish this?

2
  • I don't see your JavaScript code for that. Can you post that too? Commented Nov 13, 2014 at 20:06
  • Updated with some js Commented Nov 13, 2014 at 20:11

1 Answer 1

1

Two options are:

  1. Grab the title using a click event listener. Make an ajax get request, sending in the ID of the post. The server queries the database for that post, then sends the attributes for the post via json back to the client. Then do whatever you want with that data

  2. Dump all the attributes you need for the post on the page, but hidden. Then use the click listener to un-hide the post that was clicked on

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

2 Comments

For option 2, This is how I originally had it. But how can I dynamically add new divs for each post, then have css hide it, and js handle its actions.
option #2 is basically the approach where you dont add new divs. You create the divs with each iteration here: @posts.all.each_with_index do |post, index|, hide them with a css class, and then use JS to target that element to unhide it. Let's say each post object looks like <div class="post post-22">...</div>. You would use your click listener to grab the ID, then $(".post-$ID").show()

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.