Frage

I'm trying to put together something seems so simple but for some reason I can't get the return false; to work correctly. I am trying to stop the user from entering anymore text after the word "img" is found three times. The return false; doesn't work for some reason. I have everything working in my demo except how to stop the user from typing. Any help would be great.

DEMO: jsfiddle.net/ryanverdel/2cAeX/

$('#test').keyup(function(e){
var v = $(this).val(),
    w = v.split(/\b[\s,\.-:;]*/),
    word = 'img',
    c = 0;
for (var i=0,len=w.length;i<len;i++){
    if (w[i] === word){
        c++;
    }
    if(c == 3){
    return false           
    }
}
$('#output').text(c);
});
War es hilfreich?

Lösung

Using keyup is a bit late, as the key has already been pressed:

$('#test').keypress(function(e){
    var v = $(this).val(),
        w = v.split(/\b[\s,\.-:;]*/),
        word = 'img',
        c = 0;
    for (var i=0,len=w.length;i<len;i++){
        if (w[i] === word){
            c++;
        }

    }
    if(c == 3){
        return false           
    }
    $('#output').text(c);
});

FIDDLE

Here's an easier way:

$('#test').on('keypress', function(e){
    var word  = 'img',
        count = this.value.match(new RegExp('\\b'+word+'\\b','g')) || [];

    $('#output').text(count.length);
    return count.length < 3;
});

FIDDLE

EDIT:

As a requirement seems to be to be able to use backspace, keypress can't be used as it doesn't register backspace.
However, keydown will, and with some clever magic we can do:

$('#test').on('keydown', function(e){
    var word  = 'img',
        count = this.value.match(new RegExp('\\b'+word+'\\b','g')) || [];

    $('#output').text(count.length);
    return !(count.length > 2 && e.which != 8); // 8 is backspace
});

FIDDLE

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top