0

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?

1

4 Answers 4

1

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

onclick='showImg("<%= ep.artworkUrl30 %>");'>
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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.

Comments

0

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>
<% }); %>

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.