Vincent
Vincent

Reputation: 175

ENT_QUOTES in a JS string

I have this function :

function change_this(my_str)
{
    $('#myDiv').html('<input value=\''+my_str+'\'>');
}

When I call this function with this :

onclick=change_this('Test &#039;');

I see in the debugger that &#039; has been turned to a quote, and therefore the script does not work.

So my question is: how can I send a quote inside a string to a JS function?

I'm sure I'm not the first person to face this issue, I googled but did not find any simple explanations / answers.

Upvotes: 0

Views: 127

Answers (1)

Quentin
Quentin

Reputation: 943615

You have two problems. This is because you have HTML embedded in JavaScript embedded in HTML which you are then generating HTML from by mashing together strings of JavaScript. You switch languages so many often it makes my head spin.

Problem 1: Getting the right string into the function

To include a single quote inside a string delimited by single quotes in JavaScript, you must escape them with a \.

onclick="change_this('Test \'');"

There is no need to use character references here. There are no ' with special meaning in the HTML. You would need to use &#039; three times if you had used ' instead of " to delimit the attribute value.

I'd avoid onclick entirely and favour data- attributes and JS event binding.

<input type="button" data-foo="Test '">

$("[type=button]").on('click', function (event) {
    change_this( $(this).data('foo') );
});

Problem 2: Getting the right string into the HTML attribute value.

With the approach you are taking, you would need to convert the ' to &#039;. Note that you would have to do it programatically because if you had it in the onclick attribute then it would be converted to ' by the HTML parser before the JavaScript engine even saw it.

Don't use your current approach though. Mashing strings together to make HTML is a nightmare.

Use DOM or something jQuery that vaguely resembles DOM.

var input = $("<input />").val(my_str);
$('#myDiv').empty().append(input);

Upvotes: 1

Related Questions