Tuesday, June 4, 2013

Hitting backspace on the jquery datetime control hides it on MSCRM 2011 form/ How to capture the keypress event on a jquery control and overcome the default behavior


I have used jquery hour’s picker/Date picker control on the MSCRM form. It was working perfectly fine till the time I used to press the backspace. As soon as we press backspace it used to hide the control for some reason.

To overcome this we need to override the default behavior of the “backspace” and “delete” keys.

As shown below I am using the “keydown” event, please do not use KeyPress event as it does not gives the required result

$("#timepickerControl").keydown(function (e) {

            switch (e.keyCode) {

                case 46:  // delete

                    e.preventDefault();

                    alert("Del Key Pressed ,Please use slider to enter valid input");

                    break;

                case 8:  // backspace

                    e.preventDefault();

                    alert("Backspace Key Pressed ,Please use slider to enter valid input");

                    break;

            }

        });
The above code will stop the hiding if I click on the text box provided for the control.
In order to disable the backspace on the complete document and the parent document we need to have two extra pair of functions as below


 // Prevent the backspace key from navigating back on the webresource.

        $(document).unbind('keydown').bind('keydown', function (event) {

            var doPrevent = false;

            if (event.keyCode === 8) {

                var d = event.srcElement || event.target;

                if ((d.tagName.toUpperCase() === 'INPUT' && (d.type.toUpperCase() === 'TEXT' || d.type.toUpperCase() === 'PASSWORD'))

             || d.tagName.toUpperCase() === 'TEXTAREA') {

                    doPrevent = d.readOnly || d.disabled;

                }

                else {

                    doPrevent = true;

                }

            }

 

            if (doPrevent) {

                event.preventDefault();

            }

        });

 

    });

 

    //Prevent the backspace key from navigating back on the parent form containing the webresource.

    $(window.parent.document).unbind('keydown').bind('keydown', function (event) {

        var doPrevent = false;

        if (event.keyCode === 8) {

            var d = event.srcElement || event.target;

            if ((d.tagName.toUpperCase() === 'INPUT' && (d.type.toUpperCase() === 'TEXT' || d.type.toUpperCase() === 'PASSWORD'))

            || d.tagName.toUpperCase() === 'TEXTAREA') {

                doPrevent = d.readOnly || d.disabled;

            }

            else {

                doPrevent = true;

            }

        }

 

        if (doPrevent) {

            event.preventDefault();

        }

    });

 

No comments: