TextBox ontextChanged does not fire when user adds text

I create a text field inside the repeater similar to this (so many text fields are created inside the loop and added to the repeater control)

.aspx.cs

TextBox textBox = new TextBox(); textBox.TextChanged += new EventHandler(textBox_TextChanged); 

and I have a function like this to change the background color of the textBox to white if there is text in this text box (yellow when creating the form)

 protected void textBox_TextChanged(object sender, EventArgs e) { TextBox textBox = sender as TextBox; if (textBox.Text != String.Empty) { textBox.BackColor = System.Drawing.Color.White; } } 

but the function does not hit at all. Any pointers to what I'm doing wrong?

Thanks.

+4
source share
3 answers

I would advise to keep the return trip to the server and do it using javascript. When you create your control in code, add the onchange client event attribute and process it:

 myTextBox.Attributes.Add("onchange", "this.style.backgroundColor = (this.value != '')?'#fff':'yellow';"); 

Hope this helps!

+4
source

Java script example

 <script type="text/javascript" language="javascript"> function runScript(evt, ID) { var ctl = document.getElementById(ID.id); if (ctl.value == '') { ctl.style.backgroundColor = '#FFFF00'; } else ctl.style.backgroundColor = '#FFFFFF'; return true; } </script> 

HTML Repeater Control Sample

 <asp:Repeater ID="rpt" runat="server"> <HeaderTemplate> <table> <tr> <td> textBox </td> </tr> </HeaderTemplate> <ItemTemplate> <tr> <td> <asp:TextBox ID="ed" runat="server" BackColor="Yellow" onkeyUp="return runScript(event, this)" autocomplete="off"></asp:TextBox> </td> </tr> </ItemTemplate> <FooterTemplate> </table> </FooterTemplate> </asp:Repeater> 
0
source

Thanks guys for the help. This is the last code I used .aspx.cs.

 textBox.Attributes.Add("onkeypress","javascript:changebackgroundcolor()"); 

.aspx

 <script type="text/javascript"> function changebackgroundcolor() { var element; for (var i = 0; i < document.forms[0].elements.length; i++) { element = document.forms[0].elements[i]; switch (element.type) { case 'textarea': if (element.value.length > 0) { element.style.borderwidth = "thin"; element.style.bordercolor = "White"; element.style.borderstyle = "solid"; } break; } } } </script> 
0
source

Source: https://habr.com/ru/post/1401200/


All Articles