Restricting keyboard input with keypress jQuery

旧时模样 提交于 2019-12-02 04:57:14

Two things to help improve your game:

  1. To add a max input length on your textbox use the maxlength attribute.

    <input type="text" id="form" class="form-control" placeholder="guess" maxlength="1">

  2. To restrict only alphabetic inputs and prevent empty string guesses add the following to your (".form-control").keypress function

.

var keycode = event.keyCode ? event.keyCode : event.which;


if ((keycode < 64 || keycode > 91) && (keycode < 96 || keycode > 123) && keycode !== 13)
    return false;


if (keycode == 13) {
    var space = $(this).val().toLowerCase();

    if (space == '') {
        window.alert("Please enter a letter to guess.")
        return false;
    }

    if (wrongGuesses.indexOf(space) > -1 || rightGuesses.indexOf(space) > -1) {
        play(space);
        $(this).val('');
        endGame();
        return false;
    }
    else
        window.alert("You already guessed this letter.");
}

$.restrict() is exactly for this purpose.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!