在字段中输入文本更改div的背景颜色(Input text in field change background color of div)

编程入门 行业动态 更新时间:2024-10-26 22:19:34
字段中输入文本更改div的背景颜色(Input text in field change background color of div)

我希望只有在输入字段中有文本时才有div背景颜色更改颜色,并且当没有文本时,颜色不会改变或者它会恢复为原始颜色。 到目前为止,这是我的代码,它不起作用。

<script type="text/javascript"> $(document).ready(function () { $('#inputDatabaseName').change(function () { $(this).parent().find('#colorchange').css('background-color','#ff0000'); $(this).css('background-color','#ff0000'); }); </script> </head> <body> <form id="form1" runat="server"> <div id="colorchange"> <input id="inputDatabaseName"> <table id="searchResults"><tr><td>empty</td></tr></table> </div> </form> </body>

I want to have the div background color change colors only when there is text in the input field and when there is no text there the color doesn't change or it reverts back to the original color. Here is my code so far and it doesn't work.

<script type="text/javascript"> $(document).ready(function () { $('#inputDatabaseName').change(function () { $(this).parent().find('#colorchange').css('background-color','#ff0000'); $(this).css('background-color','#ff0000'); }); </script> </head> <body> <form id="form1" runat="server"> <div id="colorchange"> <input id="inputDatabaseName"> <table id="searchResults"><tr><td>empty</td></tr></table> </div> </form> </body>

最满意答案

我建议使用类而不是更改CSS属性。 这应该工作

$(function () { $('#inputDatabaseName').keypress(function () { var $this = $(this), $div = $(this).parent(); // Cache the jQuery selectors to make code faster if ($this.val().length > 0) { $div.addClass("hasContent"); } else { $div.removeClass("hasContent"); } }); });

现在添加一些CSS:

#colorchange { background-color: white } /* default color */ #colorchange.hasContent { background-color: red } /* updated color */ #colorchange #inputDatabaseName { background-color: white } /* default color */ #colorchange.hasContent #inputDatabaseName { background-color: red } /*updated color*/

I'd suggest using classes instead of changing CSS attributes. This should work

$(function () { $('#inputDatabaseName').keypress(function () { var $this = $(this), $div = $(this).parent(); // Cache the jQuery selectors to make code faster if ($this.val().length > 0) { $div.addClass("hasContent"); } else { $div.removeClass("hasContent"); } }); });

Now add some CSS:

#colorchange { background-color: white } /* default color */ #colorchange.hasContent { background-color: red } /* updated color */ #colorchange #inputDatabaseName { background-color: white } /* default color */ #colorchange.hasContent #inputDatabaseName { background-color: red } /*updated color*/

更多推荐

本文发布于:2023-07-28 23:41:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1310267.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字段   文本   颜色   背景   div

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!