开发者

Escaping Apostrophes in Javascript Generated From PHP

开发者 https://www.devze.com 2023-01-15 10:45 出处:网络
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 sear

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\" 
onblu开发者_高级运维r=\"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';
0

精彩评论

暂无评论...
验证码 换一张
取 消