1

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

2 Answers 2

1

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'));
});
Sign up to request clarification or add additional context in comments.

Comments

0

Try to change syntax like this: Handlebars

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.