2012-04-09 7 views
2

入力欄を空白のままにしてデータを消去すると、バックグラウンドは元の色に戻りません。入力を介してdiv背景を変更するスクリプトが必要

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

私は間違っていますか?あなたは、キーのアクションが実行される前に呼び出されkeypressを使用しているため

<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> 
+1

なぜ '.length'をもう一度テストしていますか?それが「else」の目的です。 – Blazemonger

答えて

0

この1は動作するはずです...

<script> 

$(document).ready(function() { 

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

</script> 
+0

OPがしようとしていることに対して、 'keypress'が動作するとは思わない。 –

3

問題があります。あなたがkeyupを使用した場合、これは動作します:

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

をまた、@ mblase75が指摘したように、あなたは他の条件で値のlengthをテストする必要はありません。

Example fiddle

あなたはさらに、このコードを単純化したい場合は、正の整数をtrueに同一視されるように、あなたは、単に、条件として.val().lengthと三元の文を使用することができます。

$("#id").keyup(function() { 
    $(this).css("background-color", $(this).val().length ? "red" : "grey"); 
}); 
2

あなたはでしょうここでは01だ

$(function(){ 
    $("#id").keyup(function() { 
     $("#in").css("background-color", $(this).val().length > 0 ? "red" : "grey"); 
    }); 
});​ 

:先ほど入力した文字を考慮してkeyupを使用したいです説明する。あなたのケースでは

+0

'#in'と' #id'の両方に 'this'を使用しました。 – Blazemonger

+0

それを指摘してくれてありがとう。私は私の答えを更新しました。 –

-2

使用からkeyup

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

$("#id").keyup(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

、 'キープレス' イベントは、(input.val前に呼び出さました)。長さが変更されました。 コード実行セレクタを5回取得し、insted oneを実行します。

このコードに目を向けると、それが正常に動作します:

HTML:

<input id="id" type="text" autocomplete="off"> 
<div class="in"></div>​​​ 

CSS:

.in {width:200px; height:20px; background-color:#grey;} 
.in-red {background-color:red;} 

JS:

$(function(){ 
    var $in = $('.in'); 
    $('#id').on('keyup', function(){ 
     $this = $(this); 
     if ($this.val().length > 0) { 
      $in.addClass('in-red'); 
     } else { 
      $in.removeClass('in-red'); 
     } 
    }); 
});​ 

そして、あなたがテストすることができますそれはに

関連する問題