views:

95

answers:

3

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?

A: 

How about this

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

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";
Gumbo
Awesome! Works. Thanks so much. Just change the last quote to an apostrophe.
jkeesh
+1  A: 

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).'" />';
JW