javascriptjquery

Generating HTML dynamically when quotes are involved


I have the following script:

function Start() {
    
    var TheData = 'tes"sst3\'k';
    
    var TheHTML = '<div class="SomeClass">' + TheData + '</div>';
    TheHTML += '<input type="text" id="TheTextBox" value="';
    TheHTML += TheData + '" />';
    
    $('#Dynamic').html(TheHTML);
}

Basically, I'm creating HTML on the fly and embedding some variable text into it. The problem is that the text contains quotes and the value of the textbox doesn't match the value of the label because of the quotes. How can I solve this?

enter image description here

The JS Fiddle is here.


Solution

  • Since you're using jQuery, instead of worrying about escaping the string, just do this:

    $(Start);
    function Start() {
        var TheData = 'tes"sst3\'k';
        var TheHTML = '<div class="SomeClass">' + TheData + '</div>';
        TheHTML += '<input type="text" id="TheTextBox" />';
        $('#Dynamic').html(TheHTML);
        $('#TheTextBox').val(TheData);
    }
    

    jsFiddle example