views:

193

answers:

4

My HTML is something like this :

<select>
    <option>ABC (123)</option>
    <option>XYZ (789)</option>
</select>

What I'm trying to do is: using JQuery and a regex, I replace the "(" with <span>( here's my JQuery line:

$(this).html($(this).html().replace(/\(/g,"<span>("));

It's working as intended in Firefox, chrome and safari, but (as usual) not behaving correctly on IE6/IE7 (the text after "(" just get removed)

Any thoughts ?

PS: I'm doing it this way because I need "(number") to be in a different color, and <span> in a <option> is not valid.

+2  A: 

I don't think it's the regex breaking. The below works fine in IE7:

alert("(test".replace(/\(/g,"<span>("));

What's probably happening is that IE6/7 have no clue how to render a span inside an option and just fails to display anything.

Chris Pebble
Chris may very well be correct as, i believe, even inline elements are invalid inside an OPTION element.
Dustin Hansen
A: 

I don't have IE7 but in IE6 the following

javascript:"<select><option>ABC (123)</option><option>XYZ (789)</option></select>".replace(/\(/g,"<strong>(")

yields

<select><option>ABC <strong>(123)</option><option>XYZ <strong>(789)</option></select>

And gets correctly displayed (aside that <strong> has no effect). Also works fine when using <span> instead of <strong>

jitter
+1  A: 

You're saying that span in an option is not valid, and yet that's exactly what you're trying to add. Invalid code isn't prettier just because it happens to be valid at load-time, if you know you're going to mess it upp later. So really, if that's your only concern, do add this span declaratively in your HTML, rather than injecting it later.

But if you want to fix this, I think it might help if you rewrite the regex to cover the entire tag. In a lot of cases, IE doesn't let you just change the HTML to whatever, but will use its own internal representation to fix up the code, according to its own preferences. When you write a table, for instance, IE will always internally infer a tbody, even if there isn't any in the code. In the same manner, if you inject a <span> and there's no </span>, IE might insert one by itself. To get around this, make sure you inject the code in its entirety in one go:

$(this).html($(this).html().replace(/\((.*?)\)/g,"<span>($1)</span>"));
David Hedlund
Thank you, this solved the problem, you were right about the fact that IE insert </span> by itself.
Soufiane Hassou
If it's always a number just refine the regex a little bit to $(this).html($(this).html().replace(/\((\d+)\)/g,"<span>($1)</span>")); . If it's possible to have no number do this then $(this).html($(this).html().replace(/\((\d*)\)/g,"<span>($1)</span>"));
nickyt