开发者

Simple onkeydown + length count

I have a very simple function here:

$('#input').keydown( function(e) {

    if( $(this).length === 8 ) { al开发者_如何学Pythonert('We have a winner!'); }
    else { return false; }

});

It does not work. Why? Any help much appreciated.

LIVE EXAMPLE


Assuming you want to check the length of the value of #input, then you want:

$(this).val().length

Instead of $(this).length. You also may want to get rid of the return false; as that could prevent anything from being entered into the input field.

See an updated fiddle here.

On a separate note, this will only work when there are already 8 characters in the field, and another key is pressed. That may be the way you intended it, but I think you may want the keyup event instead.


Try keyUp instead, and remove the return false branch:

$(document).ready( function(e){
    $('#input').keyup( function(e){
        if( $(this).val().length == 8 ) { alert('We have a winner!');}
    });
});


$('document').ready( function(e){

    $('#input').keydown( function(e){


        if( $(this).val().length === 8 ) { 
            alert('We have a winner!');
        }



    });
});

Use val() for first getting the value of the textbox on which the event is firing and then cal the length of the string.


When you use .length in jquery on your wrapped set, it gives you the number of elements matched from your selector: http://api.jquery.com/length/. What you want is to get the length of the value of your input (.val().length ).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜