tomaytotomato
tomaytotomato

Reputation: 4028

Escaping html element in PHP string to prevent invalid output to browser?

I am having problems echoing a string which contains a HTML select element with javascript inside

Input at Server

 echo '<select name="services" onchange="document.getElementById("services").style.display = this.options.selectedIndex ? "block" : "none";" >';

Output in Browser

<select "none";"="" :="" "block"="" ?="" services").style.display="this.options.selectedIndex" onchange="document.getElementById(" name="services"></select>

I have tried escaping the strings using \ character but nothing seems to work.

echo '<select name="services" onchange="document.getElementById(\"services\").style.display = this.options.selectedIndex ? \"block\" : \"none\";" >';

Outputs

<select \"none\";"="" :="" \"block\"="" ?="" services\").style.display="this.options.selectedIndex" onchange="document.getElementById(\" name="services"></select>

Any tricks or hacks to work around this problem?

Thanks

Upvotes: 0

Views: 265

Answers (2)

j08691
j08691

Reputation: 207901

Try:

 echo "<select name=\"services\" onchange=\"document.getElementById('services').style.display = this.options.selectedIndex ? 'block' : 'none';\" >";

Upvotes: 3

Giberno
Giberno

Reputation: 1333

echo '<select name="services" onchange="document.getElementById(\"services\").style.display = this.options.selectedIndex ? \"block\" : \"none\";" >';

Upvotes: -1

Related Questions