2013-08-01 122 views
0

我只想在輸入字段中存在文本時沒有文本,並且顏色沒有改變或者它恢復爲原始的顏色。這是我的代碼到目前爲止,它不起作用。在字段中輸入文本改變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> 
+1

您的JS甚至不似乎是有效的做到這一點。試試jsfiddle.net(jshint) – pmandell

+2

長話短說,你關閉了你的改變功能,但沒有你的就緒功能。修復並再試一次。並且在將來,請檢查您的錯誤控制檯。 – 2013-08-01 19:24:03

回答

0

我建議使用類而不是改變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*/ 
+0

你的代碼只改變了輸入字段的顏色,而不是它所在的div。 – user2607442

+0

您沒有提及更新輸入字段......我會在幾分鐘內更新。 – Webberig

+0

非常感謝,做到了。 – user2607442

0

你似乎瞄準錯誤的元素

你的選擇應該是

$(this).parent('#colorchange') 

$(this).parent()指向div id="colorchange">

而你正試圖再次找到它會搜索其子

如果你想立即反映更改使用keyup事件而不是change

另外ID應該是唯一的頁面上。

因此$('#colorchange').css(應該這樣做。

$(document).ready(function() { 
    $('#inputDatabaseName').keyup(function() { 
     var $this = $(this); 
     $colorDiv = $('#colorchange'); 
     defaultColor = 'initial'; 
     // If value is not empty assign a color 
     // otherwise this will be set to default. 
     if ($this.val() !== '') { 
      defaultColor = '#ff0000'; 
     } 
     $('#colorchange').css('background-color', defaultColor); 
     $this.css('background-color', defaultColor); 
    }); 
}); 

Check Fiddle

0

你可以用這個JavaScript

 $('#inputDatabaseName').change(function() { 
     if($(this).val() ==="") { 
      $(this).parents('#colorchange').css('backgroundColor','red');} 
     else { 
      $(this).parents('#colorchange').css('backgroundColor','green'); 
     } 
    });