Reputation: 51947
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?
The JS Fiddle is here.
Upvotes: 0
Views: 972
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
Reputation: 811
You can encode the quotes, like this:
var TheData = 'tes"sst3'k';
Upvotes: 0
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
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);
}
Upvotes: 2