简体   繁体   中英

How to call specific instance of a button from a Ruby/Rails .each loop when they all have the same class?

basically, my problem is that when I have the JS run the .click on a rails-button in an .each loop, i need a way to target the specific button associated with the same post that triggered the script.

snippet:

    <% @posts.each do |post| %>
         <td id=ahhu> <%= button_to 'Renew', [:renew, post], method: :post, class: 'my-target' %></td>

and then in the JS:

$(document).ready(function(){

  var handler = x.configure({
    token: function(token) {
  $('.my-target').click();  
  $("form").append(tokenInput).append(emailInput).submit();



 }
  });

  $('.my-target').on('click', function(e) {
// Open Checkout with further options

handler.open({
  name: 'm'
});
e.preventDefault();

});

  $(window).on('popstate', function() {
handler.close();
  });
 });</script>

First of all, you can only have one ID on an element per page. So, iterating over these and giving them the same ID of "ahhu" is pointless. Select them by class. You can use the Javascript "this" keyword with JQuery and it will maintain the scope in which it is called. For example,

<% @posts.each do |post| %>
     <td class="ahhu"> <%= button_to 'Renew', [:renew, post], method: :post, class: 'my-target' %>
</td>

Then, in the JS, you can select the specific post like this:

$('.ahhu').click(function() {
  $(this). // whatever you want to do here.
}

Try doing "console.log($(this)) and view it in your browser's console. You'll notice that the scope will change and it will only target the specific post you click on. You can do the same on "my-target" or just traverse down the DOM structure until you get the child "my-target." This is a much more dynamic way to handle specific events in javascript than adding ID's that increment in number as it iterates through.

some of my code

<input type="button" class="class1" value="123"/>
<input type="button" class="class1" value="456"/>     
list = document.getElementsByClassName('class1')

for (var i = 0; i < list.length; i++) {
    alert(list[i].value); // use your Js call here .
}

This should get going..

Couldn't you handle this with the loop in the Rails view to create a unique ID for each button?

posts.each do |post|
  link_to post.name, id: "btn-#{post.id}"
end

It's difficult to give proper guidance on this without knowing how you're trying to generate these links/buttons on the server side.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM