yamspog yamspog - 4 months ago 9
Javascript Question

how to capture key repeats with javascript

i have an asp.net form and an asp:textbox. i have a problem when the user presses and HOLDS a key down. the user selects the text box and then presses and holds '9' until the text box fills with 9s.

Is there any way to detect this situation?
Is there a way to stop key repeats when the key is held down?

Answer

Using jquery, you could do something like this:

<script type="text/javascript">

    var allowKey = true;

    $(function () {
        $("#one").keydown(function (e) {
            if (!allowKey) {
                e.preventDefault();
            }
            allowKey = false;
        });

        $("#one").keyup(function () {
            allowKey = true;
        });
    });

</script>

<input id="one" />

UPDATED BUG FIXES:

    var keyCount = 0;
    $(function () {
        $("#one").keypress(function (e) {
            if (keyCount > 1) {
                e.preventDefault();
            }
            keyCount++;
        });

        $("#one").keyup(function () {
            keyCount = 0;
        });
    });
Comments