frenchie
frenchie

Reputation: 51947

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.

Upvotes: 0

Views: 972

Answers (4)

Suman Bogati
Suman Bogati

Reputation: 6349

Here is your answer

$(Start);

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);
}

Upvotes: 0

ItsCosmo
ItsCosmo

Reputation: 811

You can encode the quotes, like this:

var TheData = 'tes&quot;sst3&apos;k';

Upvotes: 0

Greg
Greg

Reputation: 8784

It's much safer (for this exact reason) to let jQuery worry about all that and generate your HTML like this:

var $input = $("<input>").attr("id","TheTextBox").val(TheData);
var $div = $("<div>").addClass("SomeClass").text(TheData).append($input);

var $wrapper = $("<div>").append($div);
var TheHTML = $wrapper.html();

Upvotes: 3

j08691
j08691

Reputation: 207900

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

Upvotes: 2

Related Questions