I need to pass strings that may contain special characters to a Javascript function as below.
function setEditMode(countryName, countryCode)
{
document.getElementById("txtCountryName").value=countryName;
document.getElementById("txtCountryCode").value=countryCode;
}
<input id="txtCountryName" name="txtCountryName" type="text" maxlength="50"/><br/>
<input id="txtCountryCode" name="txtCountryCode" type="text" maxlength="2"/><br/>
<input type="button" value="Submit" id="btnEdit" name="btnEdit" onclick="setEditMode(''xx' "yy" # $', '"'');" />
When the button is clicked the two parameters of type string that contain special characters need to be supplied to the setEditMode() Javascript function. The strings need to be escaped. I have tried using the escape() function but it didn’t work. Is there a way to pass such parameters to a function? (I’m dealing with JSP).
[Those parameters of the setEditMode() function correspond to 'xx' "yy" # $ and "'
respectively].
The parameters you show in your sample contains html entities. Are you trying to decode them? There is no native method in Javascript to do that, but you can use the following code snippet (requires jQuery):
In your case:
Or use a generic function:
and
Or use this function: http://phpjs.org/functions/html_entity_decode:424
if you’re not in the mood for creating div tags with jQuery.
Edit: Based on your comment. Seems to be a problem with entities for
"and'in inline script. You can solve it by calling a method like this:And combine this solution with the decoding functions above if you want those ' to be decoded in the input fields.
Or more classy:
Place the script tag at the bottom of the page and it will handle all your submit buttons based on their data-countryname and data-countrycode attributes. Render them in the same way you render your data in the onclick handler.