Results 1 to 2 of 2

Thread: simple Javascript problem with Strings.

  1. #1
    Join Date
    Jun 2005
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default simple Javascript problem with Strings.

    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){
    document.write(match);
    }

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

  2. #2
    Join Date
    Dec 2004
    Location
    UK
    Posts
    2,358
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default

    Quote Originally Posted by jingleballicks
    <%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:

    Code:
    <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:

    Code:
    <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:

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

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

    Mike

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •