Search code examples
javascripthtmlhandlebars.js

Handlebars setting values in HTML attribute for JS use


I'm trying to use HandleBars to inject value in an HTML attribute to Javascript function

 <button onclick="myFunction({{val}})">add</button>

I had tested

<a href="{{url}}">{{direction}}</a>

but the first is not working


Solution

  • Not clear what you mean by "not working." (Is the template compiling at all? Is it compiling but the markup output isn't what you expected? Is it what you expected but the js event is not firing on click?)

    This seems to work ok with the latest version of handlebars: http://jsfiddle.net/8t70qtox/2/

    Note though that the function is fired in the global scope, so it has to be accessible there in order for it to run.

    In any case, it'd really be better to keep your js and templates separate: instead of an onclick handler inline, add a class and data- elements specifying anything specific to the element that the function would need such that event handlers can access it as needed.

    Handlebars:

    <button class="js-btn-clicker" data-val="{{val}}">add</button>
    

    jQuery:

    $('body').on('click','.js-btn-clicker',function(){
        var $el = $(this);
        myFunction($el.data('val'));
    });