Mike
Mike

Reputation: 235

String.Format HTML

string.format creates a very odd result on the html below. I believe it is something to do with the inline if block but I haven't figured it out yet. Please help!

String.Format(@"<input type='text' 
                       name='PostalCode' 
                       id='PostalCode' 
                       onfocus='if(this.value == '{0}') 
                                {{ this.value = ''; }}' 
                       value='{1}' 
                       class='enter-postal' />", 
              "Enter Postal Code", "Enter Postal Code")

Upvotes: 3

Views: 28005

Answers (3)

Jon Hanna
Jon Hanna

Reputation: 113242

It does nothing strange that I can see, so without knowing what you expect, I'm not sure what the problem is.

I do note a bug in onfocus='if(this.value == '{0}') {{ this.value = ''; }}' in that you've got single quotes in the attribute, and also the JS, which won't work. Try:

String.Format(@"<input type='text' name='PostalCode' id='PostalCode' onfocus=""if(this.value == '{0}') {{ this.value = ''; }}"" value='{1}' class='enter-postal' />",
"Enter Postal Code", "Enter Postal Code")

With variables rather than literals, you'd also want to do .Replace("'", "\\'") so that you don't end up with much the same issue due to an apostrophe in the data.

Upvotes: 3

AMember
AMember

Reputation: 3057

Here try this one:

String.Format(@"<input type='text' name='PostalCode' id='PostalCode' onfocus='if(this.value == ""{0}"") {{ this.value = """"; }}' value='{1}' class='enter-postal' />", "Enter Postal Code", "Enter Postal Code")

Upvotes: 2

Cam Bruce
Cam Bruce

Reputation: 5689

In your onFocus attribute, use escaped double quotes.

String.Format(@"<input type='text' 
                       name='PostalCode' 
                       id='PostalCode' 
                       onfocus=\"if(this.value == '{0}') 
                            {{ this.value = ''; }}\" value='{1}' 
                       class='enter-postal' />", 
              "Enter Postal Code", "Enter Postal Code")

Upvotes: 1

Related Questions