Not quite sure what I’m doing wrong. I have
$description = addslashes($description);
echo "<option onclick='updateTotals(`$urlOptions`,`$option_title`,`$description`)' value='".$description."' selected> ".$description."</option>";
An example of the text I’m trying to escape is
422458 - 120' Boom if NOZZLE BODIES is CR II single nozzle body
The source code shows the slashes added in, but the code isn’t acknowledging the slash?
2
Answers
If your purpose is to produce strings in a fragment of JavaScript code then you better use
json_encode()
. It escapes all characters that need to be escaped in JavaScript and also puts quotes around it producing a valid JavaScript string literal.A short fragment of PHP code is better than any explanation:
Its output is:
Check it online.
In fact,
json_encode()
is the best way to encode any data structure if your goal is to generate a fragment of JavaScript code.$description
can broke youroption
in several ways. I’s better to define a function to be calledonclick
, but going further, it’s better to trigger the functiononchange
the select.Take a look to this example: