0

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

10
  • 2
    I highly suggest you learn more about HTML and which characters are allowed in an attribute value. See w3.org/TR/html4/intro/sgmltut.html#h-3.2.2 Commented Feb 28, 2012 at 16:59
  • @hakre - valid input inside string - w3schools.com/tags/tag_select.asp - inb4 w3fools bandwagon Commented Feb 28, 2012 at 17:02
  • The input is invalid (before it gets to the PHP string). Trying to fix it up is possible (ish) but you should fix the problem at source. The attributes allowed on a select tag are irrelevant (so you've linked to an irrelevant piece of rubbish, which is doubly bad), the problem is the " characters in the values, which is a general HTML attribute rule. Commented Feb 28, 2012 at 17:05
  • @Quentin ; nope the problem is because I have used both string encasers " and ' . Nothing wrong with the html and as you can see below jo08691 answer solved my problem! Commented Feb 28, 2012 at 17:08
  • @loosebruce — What do you mean "Nope", that's what I said. Commented Feb 28, 2012 at 17:08

2 Answers 2

3

Try:

 echo "<select name=\"services\" onchange=\"document.getElementById('services').style.display = this.options.selectedIndex ? 'block' : 'none';\" >";
Sign up to request clarification or add additional context in comments.

1 Comment

@ehudokai ; calm down! go have a herbal tea!
-1
echo '<select name="services" onchange="document.getElementById(\"services\").style.display = this.options.selectedIndex ? \"block\" : \"none\";" >';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.