binary binary - 3 months ago 6
Javascript Question

Calling Javascript method in hyperlink

In my MVC Razor page, I can call Javascript method successfully in the hyperlink below:

<a id="lnkAddAccount" class="btn btn-default btn-sm" data-toggle="modal"
onclick='openModal("#div1", "#div2")'>Details
</a>


However, when having to use this hyperlink in string, I encounter "SyntaxError: expected expression, got end of script" error.

'<a title="Details" class="btn btn-sm btn-outline grey-salsa"
onclick=openModal("#div1", "#div2")><i class="fa fa-search"></i></a>'


How to call this Javascript method from the latter hyperlink?

Answer

The first issue: you removed the quotes surrounding the value of the onclick. The quotes are optional in HTML (but strongly recommended). However, when the value has spaces like in your case, the quotes are mandatory.

The second issue: you have quotes surrounding the parameters of the openModal. That's good, but if you add the quotes to solve the first issue above, you end up with quotes inside quotes, in which case, you'll have to escape the inner quotes with \.

So you have two solutions:

Solution 1 (not recommended): remove the space in the value of the onclick so you don't need to surround it with quotes:

'<a title="Details" class="btn btn-sm btn-outline grey-salsa" onclick=openModal("#div1","#div2")><i class="fa fa-search"></i></a>'

This solution will work, but not recommended because it is strongly recommended to always use quotes surrounding the values.

Solution 2: surround the value with quotes and escape the inner quotes with \:

'<a title="Details" class="btn btn-sm btn-outline grey-salsa" onclick="openModal(\'#div1\', \'#div2\')"><i class="fa fa-search"></i></a>'