Introduction:
SAPUI5 controls has been built with the necessary events required for it. However there are certain cases, in which additional browser events needs to be added to the controls. "keypress" is a sample browser event for input element. In such cases, we can include browser events using attachBrowserEvent of UI elements (wherever applicable). Adding browser events in JS views is comparatively easier than doing the same in XML views.
Purpose: To Demonstrate handling browser events in XML views
Note:
1. Please check SAPUI5 Demokit Documentation for each individual controls whether they have option to add this additional event to it.
2. To know more about additional possible events, please check :http://www.w3schools.com/js/js_events_examples.asp
Sample Scenario:
Prevent user to enter only alpha numeric value in the input field and show message as well.
Implementation:
Step 1: Create a Sample UI5 application project by selecting XML view as the view type.
Step 2: Add a Label and Input field with an id to it as below
<content>
<VBox>
<Labeltext="User ID"/>
<Input
id="myInp"
type="Text"
placeholder="Enter ID">
</Input>
</VBox>
</content>
Step 3: In Controller class, add the method onAfterRendering as below
onAfterRendering: function() {
},
Step 4: Inside onAfterRendering,get the id of input field and attach the browser event for it. Also add the logic that needs to be called when this browser event is fired. Now the method would look like:
onAfterRendering: function()
{
this.getView().byId("myInp").attachBrowserEvent("keypress",
function(event){
event.stopImmediatePropagation();
var regex = new RegExp("^[a-zA-Z0-9]+$");
var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
if (!regex.test(key))
{
sap.m.MessageToast.show("Special Characters not allowed",{
my:sap.ui.core.Popup.Dock.CenterCenter,
at:sap.ui.core.Popup.Dock.CenterCenter });
event.preventDefault();
event.stopPropagation();
returnfalse;
}
}
);
},
Step 5: Save,Build and Test locally. Output of this will block the user to enter any special characters and also throw a message in screen.
We can also define and handle the other browser events same as the above one. Give a try
Suggestions and Feedbacks are welcome!
Regards,
Meganadhan S