0

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.

2
  • javascript syntax in php? How is the related to PHP? Commented Jul 22, 2012 at 16:02
  • title edited. I meant it was being echoed in php using quotes, however, you are correct this is not about php. Commented Jul 22, 2012 at 16:14

1 Answer 1

5

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;);')
Sign up to request clarification or add additional context in comments.

4 Comments

this is all inside a php echo statement delimited with quotes so if I employ quotes, I interfere with that statement. I guess the html approach will work...I don't suppose there a way to escape the apostrophes in some way or use backicks?
@user1260310 — PHP has syntax for escaping quote characters in strings … but nesting languages inside each other is a good way to get ugly, hard to maintain code. The top option on the list of solutions is at the top for a reason. Don't use intrinsic event attributes. Do use external JavaScript. Don't put HTML in PHP strings. Do drop out of PHP mode (?>) or use a template language to output HTML.
I changed the jsfiddle to quotes but there still seems to be something wrong: jsfiddle.net/kSVVX/2
@user1260310 — You are wrapping the script in an onload function, so your function is scoped to that function. Set "no wrap" in the jsfiddle options.

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.