voltaire voltaire - 4 days ago 5
Jade Question

Jade - why only the first button in a loop is working

In a jade view template, there is a button created in a loop. The button call a function (in a public .js lib) and parameters are sent.
In the loop there are n items, n buttons but there is only one action when the first one is clicked.

each game in games
td= moment(game.game.date).format('YYYY-MM-DD h:mm:ss a')
if (game.game.users.white==user.key)
td= game.game.users.black
else
td= game.game.users.white
td= game.game.id
td
input#username(type="hidden", value="#{user.key}", name="username")
input#rgame(type="hidden", value="#{game.game.id}", name="rgame")
button#resumegame Play

Answer

You are creating buttons in a loop with the same id #resumegame. id represents a unique element, so the event you're attaching to it on click will only work on the first button#resumegame.

One way to fix this would be to use a class instead of id, something like :

each game in games
   td= moment(game.game.date).format('YYYY-MM-DD h:mm:ss a')
   if (game.game.users.white==user.key)
      td= game.game.users.black
   else
      td= game.game.users.white
      td= game.game.id
      td
           input#username(type="hidden", value="#{user.key}", name="username")
           input#rgame(type="hidden", value="#{game.game.id}", name="rgame")
           button.resumegame(data-id="#{game.game.id}") Play

And in your js, add an event listener on the class :

$('.resumegame').on('click',function(){

    var gameId = $(this).data('id');

    // Do whatever you want here, 
    // you know the id of the button that has been clicked via the data-id attribute

});
Comments