passing string argument to onclick javascript function

I am trying to pass a javascript variable to an onclick function, the function works fine with number variables but not with strings. I need to pass the attribut from an object like so:

onclick="showImg(<%= ep.trackId%>);

My showImg function accepts this attribut, but when I try passing a string like so:

onclick='showImg(\""+<%= ep.artworkUrl30 %>+"\");'>

The function simply doesn't work. Is there a way to make it work or bypass this problem?

Upvotes: 0

Views: 933

Answers (4)

Sasidhar Boddeti
Sasidhar Boddeti

Reputation: 1214

I think the ' are not closed properly please try

onclick='showImg(\"'+<%= ep.artworkUrl30 %>+'\");'>

EDIT : after viewing your code you can try

<% var epArray = episodes[0]; %>
<% _.each(epArray, function(ep){ %>
    <option value="<%= ep.trackNumber %>" onclick='showImg("<%= ep.artworkUrl30 %>");'><%= ep.trackName %></option>
<% }); %>

Upvotes: 0

sergeyz
sergeyz

Reputation: 1337

You don't want to pollute html with function calls, so do not use onclick attribute. Use javaScript to add an event listener.

var someString = "\<%= ep.artworkUrl30 %>\";
element.addEventListener('click', function(someString){
   //do something with someString
});

https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener

Upvotes: 1

bruceceng
bruceceng

Reputation: 2182

Its definitely a problem with how you are escaping the various quotes. It really depends what the context of your statement is. If you are in raw HTML then you should have:

    <body onclick='showImg("<%= ep.artworkUrl30 %>")'></body>

If you need quotes within your string then these would be:

    <body onclick='showImg("\"<%= ep.artworkUrl30 %>\"")'></body>

However if you are trying to generate HTML within javascript (like it appears you might be) then you may have to use other string escaping methods.

Upvotes: 0

Val
Val

Reputation: 2323

The ASP.NET code nuggets (<%= ... %>) are processed on the server side; no need to concatenate the quote marks. Try simply:

onclick='showImg("<%= ep.artworkUrl30 %>");'>

Upvotes: 1

Related Questions