简体   繁体   中英

If statements in onclick and onselect not working in ASP.NET

This should be pretty straight forward, but I've been researching for over a day now and can't figure out why this isn't working. I'm making a web page in ASP.NET. What I'm trying to do is have a textbox with gray placeholder text that disappears and changes the font color to black when the textbox is clicked or selected. Here's my code:

<asp:TextBox ID="addEditTextBox1" runat="server" onselect="if(style.color=='#999999'){style.color='Black'; this.value='';}" onclick="if(style.color=='#999999'){style.color='Black';this.value='';}" ForeColor="#999999" Width="250px">Revision #</asp:TextBox>

I've tried changing the "if" statement triggers to

if(style.color.value=='#999999'){...} 

and

if(ForeColor=='#999999'){...} 

and

if(ForeColor.value=='#999999'){...} 

and many other syntaxes but I can't find one that works. I do know the onclick and onselect statements are working because if I replace the "==" with a "=" they trip 100% of the time, but that completely negates the whole idea of an "if" statement. I'm new to ASP.NET and JavaScript, so maybe there's something obvious I'm missing, but I can't find it anywhere. Here's some other information that I didn't think was relevant but may be helpful:

  • Running in Visual Studio Professional 2012
  • This is towards the top of the page's source code:

     <html xmlns="http://www.w3.org/1999/xhtml"> 
  • Target Framework: .NET Framework 4.5.

Feel free to inquire if I left anything out. Thanks!

Either just simply use a HTML5 placeholder attribute, all the browsers support it now.

Or use this, works for both keyboard tabbing and mouse clicking:

<asp:TextBox ID="addEditTextBox1" runat="server" onfocus="this.onfocus = null; this.value = ''; this.style.color = 'black';" ForeColor="#999999" Width="250px">Revision #</asp:TextBox>

Btw, onclick is really just for buttons, you probably meant onmousedown and onkeydown - onselect is for when selecting text (to prevent it for example).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM