Search code examples
phpjavascripttextfieldescapingapostrophe

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?


Solution

  • 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";