How to do post-back when user hits enter on a text box

You can use the onkeypress client-side event, then call __doPostCallBack passing the control’s name as argument for eventTarget.

<%@ Page Title="Home Page" Language="C#" %>

<script runat="server">
    protected void Page_Load(object sender, EventArgs e)
        lblKeyword.Text = txtSearch.Text;

        lblKeyword_RequestForm.Text = Request.Form[txtSearch.UniqueID];

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "">
<html xmlns="" xml:lang="en">
<head id="Head1" runat="server">
    <link href="~/Styles/Site.css" rel="stylesheet" type="text/css" />
    <script src="Script.js" type="text/javascript"></script>
    <form id="frmTest" runat="server">
    <div class="page">
    <div class="main">
        <h2>Welcome to ASP.NET!</h2>

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

        <asp:Label ID="lblKeyword" style="width:178px;" runat="server" />
        <p />
        <asp:Label ID="lblKeyword_RequestForm" style="width:178px;" runat="server" />

The Script.js file:

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;
}; //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) {
        return onEnterFunction(element.value);
    else {
        return true;

//call our function. In this example, Keyword argument is not necessary, it is here for illustration purposes
function thisSearch(keyword) {
    return false;

For how to call client-side function 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.

Leave a Reply

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

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

Google photo

You are commenting using your Google 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 )

Connecting to %s