Friday, August 26, 2016

Add onkeypress event to server control

Suppose you need to use a client side function when the enter key is pressed in a  a server control. This is how it can be done with a few lines of javascript code:

 function handle(e) {
     if (e.keyCode === 13) {
     var linkUrl = document.getElementById("txtLinkUrl").value;
     var linktext = document.getElementById("txtLinkText").value;
     var mylink = "<a href='" + linkUrl + "'>" + linktext + "</a>";
     var txtWriteValue = document.getElementById("txtWrite").value;
     document.getElementById("txtWrite").value = txtWriteValue + " " + mylink;
     document.getElementById("lblActive").innerText = txtWriteValue + " " + mylink;
     }
     return false;
     }

The function converts values from two textboxes into a hyperlink. The event handler is added as an attribute to a server control where the enter key is pressed:

txtWrite.Attributes.Add("onkeypress", "handle(event)")

This function does not perform any error checking, so you need to customize it to be more robust.







No comments:

Post a Comment