Single quotes splitting JavaScript string

When I put a single quote in the textbox, it doesn't appear in the dynamically added textbox. See next example:

$("#abc").before("<div><input type='text' value='" + $scope.txt + "'/></div>");

      

http://jsfiddle.net/U3pVM/15777/

+3


source to share


5 answers


I had a similar problem a while ago and found this answer at fooobar.com/questions/184108 / ...

See the quoteattr function for what you need: http://jsfiddle.net/U3pVM/15780/



function quoteattr(s, preserveCR) {
    preserveCR = preserveCR ? '&#13;' : '\n';
    return ('' + s) /* Forces the conversion to string. */
        .replace(/&/g, '&amp;') /* This MUST be the 1st replacement. */
        .replace(/'/g, '&apos;') /* The 4 other predefined entities, required. */
        .replace(/"/g, '&quot;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        /*
        You may add other replacements here for HTML only 
        (but it not necessary).
        Or for XML, only if the named entities are defined in its DTD.
        */ 
        .replace(/\r\n/g, preserveCR) /* Must be before the next replacement. */
        .replace(/[\r\n]/g, preserveCR);
        ;
}

      

+3


source


Try this, I assumed you want the quoted text to be added and displayed without quotes.



 function TodoCtrl($scope) {
  $scope.txt = "";
    $scope.addBefore = function() {
        $("#abc").before("<div><input type=\"text\" value=" + $scope.txt + "></div>");
    };
}

      

0


source


Try replacing _'_

with <code>&ampapos;<code>

or _"_

with<code>&ampquot;<code>

JSFiddle

    function TodoCtrl($scope) {
     $scope.txt = "";
     $scope.addBefore = function() {
        $("#abc").before("<div><input type='text' value='" + $scope.txt.replace("'","&apos;") + "'/></div>");
    };
}

      

0


source


function TodoCtrl($scope) {
  $scope.txt = "";
    $scope.addBefore = function() {
        $("#abc").before('<div><input type="text" value="' + $scope.txt + '"></div>');
    };
}

      

just change from double to single

http://jsfiddle.net/U3pVM/15784/

0


source


I did this by replacing the single or double request with the equivalent HTML code.

0


source







All Articles