View Full Version : simple Javascript problem with Strings.

06-13-2005, 10:01 AM
right. im new to Javascript.
im getting an annoying problem with passing Strings to
a javascript function from jsp.

<%String match = "test"%>

<td> <a href="#" onClick="return rateSelection(<%=match%>)">Rate </a></td>

and the javascript:

function rateSelection(match){

could someone tell me what im doing wrong here because it doesnt
i apologise for my ignorance.

06-16-2005, 01:03 AM
<%String match = "test"%>

<td> <a href="#" onClick="return rateSelection(<%=match%>)">Rate </a></td>If you view the source within a browser, the problem should be clear. The server will output:

<a href="#" onclick="return rateSelection(test)">Notice that the word 'test' isn't quoted - it will be treated as an identifier (and one that doesn't exist).

Include quotes around the insert:

<a href="#" onclick="return rateSelection('<%=match%>')">and you should get the expected result.

Note that quotes embedded within the server-written string can cause trouble as you could end up with, for example: 'It's gonna fail'. The nested single quote will cause a syntax error. You would need to include literal backslashes in match that can act as escapes in the script:

<%String match = "It\\'s gonna work!"%>The output here would be:

... onclick="return rateSelection('It\'s gonna work!')"which is fine.