Jack
Jack

Reputation: 1

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?

Upvotes: 0

Views: 65

Answers (3)

Racil Hilan
Racil Hilan

Reputation: 25351

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>'

Upvotes: 1

atul
atul

Reputation: 562

Try this

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

don't give line break in between or else concatenation with line break

Upvotes: -1

Jeremy J Starcher
Jeremy J Starcher

Reputation: 23863

You need quotes.

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

Notice that had to escape the inner quotes.

On the whole, making HTML from strings is just messy. Depending on your tech stack there are usually better ways.

Upvotes: 1

Related Questions