Swadeshi
Swadeshi

Reputation: 1672

Handle Special characters in Jquery template

When row[1] is Swap'nil it throws error in the console:

Uncaught Syntax Error: missing ) after argument list.

How can I handle such special characters in jQuery so that I am able to call testFunction() with the given name?

<script type="text/x-jquery-tmpl" id="tmplTest">
  {{each(i, row) data}}
    <a href="javascript:void(0)" onclick='javaScript:testFunction('\${row[1]}');'>Click here</a>
  {{/each}}
</script>
function testFunction(name) {
  alert("test");
}

Upvotes: 0

Views: 120

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337560

You can both avoid the problem and improve your logic by using unobtrusive JS to attach your events, instead of the outdated on* event attributes. You can also use a data attribute to store the value you require.

As you've already included jQuery in the page, try this:

$(function() {
  $(document).on('click', '.link', function(e) {
    e.preventDefault();
    var name = $(this).data('name');
    console.log(name);
  });
});
<script type="text/x-jquery-tmpl" id="tmplTest">
  {{each(i, row) data}}
    <a href="#" data-name="${row[1]}" class="link">Click here</a> 
  {{/each}}
</script>

Note that you may still need to HTML encode the value you place in the data attribute. Your templating library should have instructions on how to do that.

Upvotes: 1

Related Questions