Search code examples
htmlstringjspquotesdouble-quotes

Handling three types of quotes


I have a JSP File which also uses JavaScript for some operations. To Display a filled textinput-field I use:

String s="theValue";
out.println("<input type='text' value='"+s+"' name='nameField' id='name' onchange=doSomething('str2','str1')/>");

But it won't work if I don't put the doSomething(str1,str2) under qoutes.

Am I forced to use three types of quotes? Is there a different way to solve this problem?


Solution

  • I'm not a JSP expert but can you not just escape the quotes like this?:

    out.println("<input ... onchange=\"doSomething('str2','str1')\"/>");
    

    Or alternatively switch your quotes round:

    out.println('<input type="text" value="'+s+'" ... onchange="doSomething(\'str2\',\'str1\')"/>');
    

    Or alternatively use templating and only output dynamic content where necessary and have the rest as standard HTML.

    <input type="text" value="<%= s %>" onchange="doSomething('str1', 'str2)"/>