1

I have a dynamically created table that has buttons associated. I would like a simple JavaScript method that would apply to every single button. Right now, it only references the first button created.

<table>
<tbody>
<% @task.subtasks.each do |subtask| %>
   <tr>
     <td>
        <button class="btn btn-default" id="collapseBtn"><span class="glyphicon glyphicon-plus" id="collapseSpan"></button>
  </td>
     <td> <%= subtask.name %></td>
   </tr>
<%end%>
</tbody>
</table>

<script>
   $("#collapseBtn").click(function(){
       $("#collapseSpan).toggleClass("glyphicon-plus glyphicon-minus");
    });
</script>
jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • What if you add a class like `collapse-btn` and try to select on class instead of id? – lintmouse Mar 02 '16 at 15:39
  • Possible duplicate of [Event binding on dynamically created elements?](http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – Tennyson H Mar 02 '16 at 16:33

2 Answers2

2

id property must be unique for any element on html page, so you need to add some class to detect your buttons when lot of them. And then handle buttons by that class

$(".buttonClass").on('click', function(e){
    $(this).find('span').toggleClass("glyphicon-plus glyphicon-minus");
});
MysterX
  • 2,318
  • 1
  • 12
  • 11
1

I see you are using jQuery.
You can select all buttons in jQuery with

$( ":button" )

instead of using one ID $("#collapseBtn").

And then use $(this) inside you function to reference it.

source: http://api.jquery.com/button-selector/

stallingOne
  • 3,633
  • 3
  • 41
  • 63