Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / productivity / SharePoint

SharePoint Control Overrides My JavaScript Keypress Event

0.00/5 (No votes)
14 Aug 2013CPOL 7.6K  
SharePoint control overrides my JavaScript Keypress event.

When you want to bind an event handler to the "keypress" JavaScript event, or trigger that event on an element, you can achieve this using jQuery handler like .keypress( handler(eventObject) ).

For example, binding "keypress" event to a text box on your custom control :

JavaScript
$("#input").keypress(function (event) {
var code = (event.keyCode ? event.keyCode : event.which);
 if(code == 13) //Enter keycode
 // your logic here...
}
});

As you can see, the task is very simple and straightforward, but when dealing with SharePoint , sometimes things get pretty messy.

Scenario:  You developed a custom control with a text box and used a "keypress" JavaScript event to trigger the “Enter” key press event. You added the control to SharePoint page and it worked, but after adding a SharePoint OOTB control that also has a text box , your "keypress" event automatically stops working. Why you ask? , well, it’s all about priorities , if your JS code is last in order,  then your code would probably work, but you can never be sure.

Solution: Use the event.preventDefault() method to stop the default action of the event, in our case, SharePoint OOTB controls.

JavaScript
$("#input").keypress(function (event) {
var code = (event.keyCode ? event.keyCode : event.which);
 if(code == 13) //Enter keycode
//stop the default action of the Enter key 
 event.preventDefault();
 // your logic here...
}
});

This way, we gained control over our events and managed to keep the OOTB functionality working.

Hope you find this article handy .

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)