SamuraiJack
SamuraiJack

Reputation: 5549

Restricting user from entering specific character in dynamically generated textboxes

I am trying to prevent user from entering two specific characters in any of the textboxes on the page. The code I am using does not work with dynamically appended textboxes.

DEMO

  window.onload = function () {
            $("input").keypress(function (e) {
                if (e.which === 44 || e.which === 124) {//preventing , and |
                    e.preventDefault();
                }
            });
}

And since I am not using server controls I can not use ajax filter etc. I would like to have a simple solution to this. Without causing any conflicts in the code. Thank you.

Upvotes: 0

Views: 123

Answers (3)

Miqdad Ali
Miqdad Ali

Reputation: 6147

Demo: http://jsfiddle.net/4v78q/

http://jsfiddle.net/4v78q/1/

$(document).ready(function(){
    $("input").each(function(){
        $(this).keypress(function(e){
            var keycode = e.which || e.keyCode; 
             if (keycode === 44 || keycode === 124) {
                 e.preventDefault();
             }
        });
    });
});

Upvotes: 0

Balachandran
Balachandran

Reputation: 9637

use event delegation for dynamically created dom

$(document).on("keypress","input",function (e) {
                if (e.which === 44 || e.which === 124) {
                    e.preventDefault();
                }
            });

document use immediate parent selector which is static in html

Upvotes: 1

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67217

Try to use event-delegation in this context, since you need to bind events for the elements which are being appended at the run time.

 $(document).on('keypress',"input",function (e) {
       if (e.which === 44 || e.which === 124) {
            e.preventDefault();
       }
 });

Side Note: I just use document for delegating the event, but you should probably use any closest static parent to the input element, in order to attain a performance boos up.

Upvotes: 3

Related Questions