Rbex
Rbex

Reputation: 1539

JQuery on event and delegation doesn't work in a jQuery function

This doesn't work on the dynamically populated elements. The website is http://bobbygerez.0fees.net/enroll_now . If you click add more and type number it doesn't work anymore.

enter image description here

            (function( $ ){
            $.fn.alphaSpace = function(e){
                var arr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ";
                var code;
                if (window.event)
                    code = e.keyCode;
                else
                    code = e.which;
                var char = keychar = String.fromCharCode(code);
                if (arr.indexOf(char) == -1){
                    return false;
                }

            }

 $('.sParent').on('keypress', '.siblings_fullname, .siblings_age',  function(e){
               return $(this).alphaSpace(e);
            });

Upvotes: 1

Views: 28

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388446

The problem seems to be in $('.sParent'), in your code the element .sParent also is create dynamically.

Even when using event delegation syntax the handler should be added to an element which is already existing in the dom when the event registration is happening. In your case I think the element #siblingParent can be used.

$('#siblingParent').on('keypress', '.sParent .siblings_fullname, .sParent .siblings_age', function (e) {
    return $(this).alphaSpace(e);
});

Also I think you can simplify your alphaSpace method, since it is not dealing with any dom you can develop it as a utility method also it can be simplified

$.alphaSpace = function (e) {
    // e.which is normalized by jQuery so no need to use e.keyCode
    var char = keychar = String.fromCharCode(e.which);
    //use a simple regex
    return /a-z\s/i.test(char)
}

then use it like

return $.alphaSpace(e);

Upvotes: 1

Related Questions