user1260310
user1260310

Reputation: 2227

javascript syntax for passing variables to function

I have a JavaScript hyperlink that is not passing variable to function, undoubtedly due to syntax. Can someone please spot error.

jsfiddle: http://jsfiddle.net/kSVVX/

js

function follow(id){
    alert(id);
}

html

<a href='javascript:void(0);' onclick= 'follow('1');'><img src='images/test.gif' border=0 alt='follow'></a>

Note: The reason that I am using all apostrophes is that this link is actually getting echoed from php where a long string is enclosed in quote marks (as certain things in the string must be in apostrophes.) I have a feeling this is source of problem, but have not succeeded in solving it by changing punctuation around.

Thanks for any suggestions.

Upvotes: 0

Views: 335

Answers (1)

Quentin
Quentin

Reputation: 944442

You are using ' characters to delimit your JavaScript string and the HTML attribute value it is embedded in.

This results in:

onclick= 'follow('

Either:

  • Avoid intrinsic event attributes (which you should be doing anyway, unobtrusive JavaScript is recommended).
  • Use different characters to delimit the attribute value (onclick="follow('1');") or string (onclick= 'follow("1");')
  • Use HTML entities to include the quote mark you are using in the data for the attribute value (onclick= 'follow(&#39;1&#39;);')

Upvotes: 5

Related Questions