2012-04-09 15 views
0

入力フィールドを含むDIVの背景色を変更したいと思います。入力にデータを入力すると、背景色が赤く変わるので、コードが正しく機能しています。しかし、私が戻って、入力フィールドを空白のままにしてデータを消去すると、背景は元の色に戻りません。入力経由でdiv背景を変更するスクリプトが必要です。

空白のときに元の色に戻すには、DIVの背景色が必要です。

私は間違っていますか? JavaScriptでif文の周りに括弧を省略することはありません、また

else { 
if($("#id").val().length == 0) 

else { 
if($("#id").val().length = 0) 

は次のようになります。

<script> 
$(document).ready(function(){ 

$("#id").keypress(function() { 
if($("#id").val().length > 0) $("#in").css("background-color", "red"); 
else { 
    if($("#id").val().length = 0) $("#in").css("background-color", "grey"); 
} 

}); 
}); 
</script> 

答えて

0

あなたはバグがあります。ここでは

は私のコードです。

0

$(document).ready(function(){ 

$("#id").keypress(function() { 
if($("#id").val().length > 0) $("#in").css("background-color", "red"); 
else { 
    if($("#id").val().length == 0) $("#in").css("background-color", "grey"); 
} 

}); 
}); 
0

上記のバグに加えて、これを試してください。

.greyColor 
{ 
background-color: grey; 
} 

.redColor 
{ 
background-color: red; 
} 

そして、あなたのjavascriptのaddClassとremoveClass機能で使用します:

<script> 
$(document).ready(function(){ 
$("#id").keypress(function() { 
if($("#id").val().length > 0) 
{ 
    $("#in").addClass("redColor"); 
} 
else { 
    if($("#id").val().length == 0) 
{ 
$("#in").addClass("greyColor"); 
$("#in").removeClass("redColor"); 
} 
} 

}); 
}); 
</script> 
は、あなたのCSSファイルでこれら2つのクラスを置きます
関連する問題