How to call client-side function when user hits enter on a text box

You can use the onkeypress client-side event:

<asp:TextBox ID="txtSearch" style="width:178px;" runat="server"
   onkeypress="return checkEnter(event, this, function(v) { thisSearch(v); });" />

<script type="text/javascript">
var theForm = document.forms[0]; //change the pointer to the form here

if (!theForm) {
    theForm = document.ctl01;
}
function __doPostBack(eventTarget, eventArgument) {
    if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
        theForm.__EVENTTARGET.value = eventTarget;
        theForm.__EVENTARGUMENT.value = eventArgument;
        theForm.submit();
    }
}; //same doPostBack method created by ASP.NET


//our method to check when user hit <Enter>
function checkEnter(e, element, onEnterFunction) {
    var characterCode;

    if (e && e.which) {
        e = e;
        characterCode = e.which;
    }
    else {
        e = event;
        characterCode = e.keyCode;
    }

    if (characterCode == 13) {
        onEnterFunction(element.value);
        return false;
    }
    else {
        return true;
    }
};

function thisSearch(keyword) {
    alert('hello World, here is the keyword:' + keyword);
};
</script>

For how to do post-back when user hits enter on a text box, go to this post.

For how to call a code-behind event/method when user hits enter on a text box, go to this post.

Advertisements

2 thoughts on “How to call client-side function when user hits enter on a text box

  1. When I initially commented I clicked the “Notify me when new comments are added” checkbox and now each time
    a comment is added I get several e-mails with
    the same comment. Is there any way you can remove people from that service?
    Thanks a lot!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s