Iladarsda
Iladarsda

Reputation: 10692

Simple onkeydown + length count

I have a very simple function here:

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

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

});

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

LIVE EXAMPLE

Upvotes: 1

Views: 13653

Answers (4)

Mark Bell
Mark Bell

Reputation: 29775

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!');}
    });
});

Upvotes: 3

kinakuta
kinakuta

Reputation: 9037

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 ).

Upvotes: 1

sushil bharwani
sushil bharwani

Reputation: 30217

$('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.

Upvotes: 2

James Allardice
James Allardice

Reputation: 166071

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.

Upvotes: 4

Related Questions