Allow text box only for letters using jQuery?

后端 未结 11 1606
情书的邮戳
情书的邮戳 2020-11-29 04:42

I want to make a text box allow only letters (a-z) using jQuery. Any examples?

11条回答
  •  伪装坚强ぢ
    2020-11-29 05:14

    Solution described by @dev-null-dweller is working absolutely.

    However, As of jQuery 3.0, .bind() method has been deprecated. It was superseded by the .on() method for attaching event handlers to a document since jQuery 1.7, so its use was already discouraged.

    Check deprecated methods list for jQuery 3.0 here: http://api.jquery.com/category/deprecated/deprecated-3.0/

    So the solution is to use .on() method instead .bind().

    If you need to bind existing elements then the code will be :

    $('.alphaonly').on('keyup blur', function(){
        var node = $(this);
        node.val( node.val().replace(/[^a-z]/g,'') ); 
    }); 
    

    If you need to bind to dynamic elements the code will be :

    $(document).on('keyup blur', '.alphaonly', function(){
        var node = $(this);
        node.val(node.val().replace(/[^a-z]/g,'') );
    });
    

    You need to bind the event to document or some other element that already exist from the document load.

    Hope this is helpful for new version of jQuery.

提交回复
热议问题