简体   繁体   中英

Escaping Apostrophes in Javascript Generated From PHP

I am trying to have a textfield with an initial value, where if you click on it, the text disappears, and if you click out before anything has been entered the initial value returns much like the search box on Yahoo answers and many other sites.

echo "<input type=\"text\" 
onblur=\"if (this.value == '') {this.value = '$cleaned';}\" 
onfocus=\"if (this.value == '$cleaned') {this.value = '';}\" 
value=\"$cleaned\" />\n";

I have a php variable $cleaned as my initial value. This code works, except for the case when the variable cleaned has an apostrophe in it, like $cleaned = "FRIEND'S" . Then the code would read this.value = 'FRIEND'S' and the apostrophe in FRIEND'S ends the string early.

I have tried using html entities, escaping the apostrophe, and using escaped quotes and cannot get this case to work. The only solution I have so far is to replace apostrophes with characters that look like apostrophes.

Does anyone know how to handle this case?

Use json_encode to encode the data to be used in JavaScript and htmlspecialchars to encode the string to be used in a HTML attribute value:

echo '<input type="text"
onblur="'.htmlspecialchars("if (this.value == '') {this.value = ".json_encode($cleaned).";}").'" 
onfocus="'.htmlspecialchars("if (this.value == ".json_encode($cleaned).") {this.value = '';}").'"
value="'.htmlspecialchars($cleaned).' />'."\n";

But using defaultValue is certainly easier:

echo '<input type="text"
onblur="'.htmlspecialchars("if (this.value == '') {this.value = defaultValue;}").'" 
onfocus="'.htmlspecialchars("if (this.value == defaultValue) {this.value = '';}").'"
value="'.htmlspecialchars($cleaned).'" />'."\n";

First generate the pure JavaScript code. You can create valid JavaScript values by using json_encode , like this:

$js = 'if (this.value == '.json_encode($cleaned).') {this.value = "";}';

Then generate the HTML. You can encode all HTML attributes, including those that contain inline JavaScript code, using htmlspecialchars , like this:

echo '<input type="text" onblur="'.htmlspecialchars($js).'" />';

How about this

echo '<input type="text" 
onblur="if (this.value == "") {this.value = "' . $cleaned . '";}" 
onfocus="if (this.value == "' . $cleaned . '") {this.value = "";}" 
value="' . $cleaned . '" />\n';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM