Search code examples
javascriptjqueryajaxstringapostrophe

Refactor javascript to avoid apostrophes causing issues?


I have taken over a website and there is a lot of javascript that looks like this;

 function BuildHTMLString(item)
 {  
       return "<input name='Text' Type='text' value='" + item+ "' />";
 }

these strings are then being used in posting forms. I realized that if the variable item has an apostrophe in it, this whole thing breaks down.

What is a recommended way to programatically populate textboxes that will be part of a form post that doesn't create an issue with names with apostrophe in it.


Solution

  • You could use document.createElement to create elements programmatically and then use the outerHTML property:

    function buildHtmlString(item) {
        var element = document.createElement("input");
        element.setAttribute("name", "Text");
        element.setAttribute("type", "text");
        element.setAttribute("value", item);
    
        return element.outerHTML;
    }
    

    On Chrome, buildHtmlString("this has a quote \""); gives me:

    <input name="Text" type="text" value="this has a quote &quot;"> 
    

    I noticed that you added the jquery tag. So you can do this pretty easily with jQuery as well:

    function buildHtmlString(item) {
        return jQuery("<input>").attr("name", "Text")
                                .attr("type", "text")
                                .attr("value", item)
                                .get(0).outerHTML;
    }