0

How do I pass the element that is being loop to event handler.

foo.hbs

<div>
    {{#each products}}
        // some html code
        <p>{{this}}</p>                            <!-- output product object -->
        <button onclick="foo(this)">Add</button>   <!-- output button object-->
        <button onclick="foo({{this._id}})">Add</button>   <!-- uncaught syntax error -->

    {{/each}}
</div>

<script type="text/javascript">
    function foo(product) {
        console.log(product);
    }
</script>

The above code: product argument gives me the HTMLButton instead of product of current iteration.


Question: How do I pass product instead of button element to the handler?
I'm using express-handlerbars.

Sithideth Bouasavanh
  • 1,011
  • 1
  • 11
  • 20

1 Answers1

0

You can try :

this.parentNode

which refers to html parent.

and in your function:

console.log(product.id);

console.log(typeof(product)); //display object

Console print html, but product is object you sent from onclick. So you can access to any related properties.

Hope it can help.

Plaute
  • 4,669
  • 2
  • 17
  • 19