How can I initiate a button click event in aspx by pressing the "Enter" key on a textbox, with the button click event being defined in the source cs file?

I am trying to trigger the btnSearchSuiteGroup_Click event when the "enter" key is pressed on the txtSuiteGroupName textbox in the aspx file. Below is the code snippet:

<asp:TextBox ID="txtSuiteGroupName" runat="server" clientidmode="Static" CssClass="DD" onkeypress="return searchKeyPress(event)"></asp:TextBox>
<asp:Button ID="btnSearchSuiteGroup" runat="server" Text="Search"  CssClass="DD" Width="64px" onclick="btnSearchSuiteGroup_Click" />
<script type="text/javascript">
    function searchKeyPress(e) {

        // look for window.event in case event isn't passed in
        if (typeof e == 'undefined' && window.event) { e = window.event; }
        if (e.keyCode == 13) {
            document.getElementById('<%=btnSearchSuiteGroup.ClientID%>').click();
        }
    }
</script>

The functionality for btnSearchSuiteGroup_Click is defined in the source cs file as follows:

protected void btnSearchSuiteGroup_Click(object sender, EventArgs e)
{
    this.LinqDataSource1.WhereParameters["SuiteGroupName"].DefaultValue = this.txtSuiteGroupName.Text;
    this.GridView1.DataBind();
    if (GridView1.Rows.Count == 0)
        Response.Write("<script language='javascript'>window.alert('No record found!')</script>");
}

However, when browsing the website, the key press event on the textbox is not initiating the button click event. Is there something wrong in the code?

Answer №1

By utilizing the Panel element, there is no need for any additional javascript functions. You can define the default button Id for the panel as shown below:

    <asp:Panel runat="server" DefaultButton="btnSearchSuiteGroup">
       <asp:TextBox ID="txtSuiteGroupName" runat="server" clientidmode="Static" CssClass="DD">          
       </asp:TextBox>
        <asp:Button ID="btnSearchSuiteGroup" runat="server" Text="Search"  CssClass="DD" Width="64px" onclick="btnSearchSuiteGroup_Click" />
        </asp:Button>
    </asp:Panel>

It is possible to have multiple panels on a single page, each with different default buttons assigned to them!

For more information regarding the Panel.DefaultButton Property

Answer №2

To optimize the process, follow these steps: 1. Define a function called 'ButtonClick' and transfer all the code from the 'btnSearchSuiteGroup_Click' function to it. 2. Set up the 'onkeypress' event for the 'txtSuiteGroupName' textbox, take a look at this discussion for guidance. 3. Upon triggering the event above, check if the pressed key is 'Enter'. 4. If the key corresponds to 'Enter', execute the 'ButtonClick' function.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The div containing the AJAX POST success message suddenly vanishes within moments of being uploaded

Encountering an issue following a successful AJAX post, where the updated div disappears shortly after Here are the jquery/PHP/POST data in sequence. Button On Click Function: function Delete_ID(clickBtnValue,clickBtnID,clickBtnName) { var my_data = {& ...

Is it possible that the images are unable to load on the page

The frontend code successfully retrieves the image links sent by the backend but encounters issues displaying them. Despite confirming that the imgUrl data is successfully fetched without any hotlink protection problems, the images are still not appearing ...

Unable to establish proper functionality of username variables in Node.js chat application

For my latest project, I am developing a chat application in node.js following a tutorial from socket.io. The main objective of the app is to allow users to input their username along with a message, which will then be displayed as "username: message" in t ...

Selenium in C# causing memory leaks with ChromeDriver

I am in need of help as I have observed that the selenium chromeDriver in C# is not releasing memory properly. I have been using RamMap to monitor memory usage. Memory usage does not steadily increase when the following scripts are not running. When runni ...

Struggling with rendering an HTML element utilizing jQuery's attribute functionality, encountering issues exclusively in Internet Explorer version

I need assistance with generating and inserting an HTML element using jQuery. In my code, I am including a class attribute for the element as shown below: jQuery('<li></li>', { class: "myClass" }); However, when testing in IE ...

When the page is reloaded, JavaScript code remains unprocessed

Within a mobile website, there is a JavaScript snippet that appears as follows: <script type="text/javascript"> (function() { // actual function code is not shown here }()); </script> Upon initial page load, the code is successfully execute ...

Having trouble reading the file using jQuery in Internet Explorer 8 and earlier versions due to its non-XML format (albeit resembling XML)

Currently, I am utilizing AJAX to load a KML file (which essentially functions as an XML file). The parsing works seamlessly in IE9, FF, and other browsers, but encounters issues in IE8. Although the data is retrieved, I face difficulties parsing it in jQu ...

Unable to connect to server using React-Native fetch. Localhost is not being used

I recently encountered an issue with my app where the fetch function used for user authentication stopped working. Despite not making any changes, the transition from React 0.27 to 0.28 seemed to have caused this problem. After scouring through numerous S ...

Sending information to a subpage through props using a query in the URL triggers a 431 Request Header Fields Too Large error

I have a page called campaigns, and I am facing an issue on the index page where I want to pass data to my dynamic page [campaignId].tsx. Although I can see the data on my dynamic page, the URL links are becoming too long, leading to an HTTP Status code 4 ...

What is the best way to keep a checkbox unchecked after clicking cancel?

I'm working on a bootbox script that triggers a customized alert. I need the checkbox that triggers the alert to be unchecked when the user clicks cancel. Here is the checkbox when it's checked <div class="checkbox"> <label> ...

Learn how to transform a raw readme file into an HTML formatted document using AngularJS, after retrieving it from GitHub

Can someone help me figure out how to format each line of the README.MD raw file into an HTML document using the controller below? angular.module('ExampleApp', []) .controller('ExampleController', function($scope, Slim,$sce) { ...

How can I permanently disable a Bootstrap button on the server side using PHP after it has been clicked once?

I am in search of a way to disable a bootstrap button permanently after it has been clicked once. While I am aware of how to achieve this on the client side using JavaScript, the button becomes enabled again after the page is refreshed. I am now looking ...

The response from Moment.js shows the date as "December 31, 1969."

Currently, I am in the process of recreating one of FCC's backend projects: Upon testing my code, I noticed that when I input the following URL: http://localhost:3000/1 The result is as follows: {"unix":"1","natural":"December 31, 1969"} var e ...

Intermittent Cloudfront Content Delivery Network (CDN) disruptions (monitoring) - Implementing CDN Fail

Over the past two months, I've been dealing with sporadic issues involving Amazon Cloudfront. These failures occur 2-3 times a week, where the page will load from my web server but assets from the CDN linger in pending status for minutes at a time. It ...

Having difficulty adding items to the shopping cart

While working on a simple checkout system using django and react, I encountered an issue. Upon clicking the add to cart button, instead of adding the item to the cart as intended, I receive a 404 page not found error. I suspect that the problem may lie in ...

Steps to deactivating a styled button using React's styled-components:

I've created a very basic styled-components button as follows: import styled from 'styled-components'; const StyledButton = styled.button``; export const Button = () => { return <StyledButton>Default label</StyledButton> ...

Issue with the System.Web.HttpRequestValidationException

I've been grappling with an issue related to a week-long problem that involves the error message System.Web.HttpRequestValidationException: A potentially dangerous Request.Form value was detected from the client. This issue arises specifically when de ...

Eliminating a pattern with underscore.js or jquery - the complete guide

I am looking to remove the ellipses (...) from a value such as ...India. How can I achieve this using underscore.js, jQuery, or JavaScript? Any tips on how to accomplish this would be greatly appreciated! ...

Troubleshooting a Peculiar Problem with Form Submission in IE10

Please take a look at the code snippet provided below: <!DOCTYPE html> <html> <body> <form name="editProfileForm" method="post" action="profileDataCollection.do"> <input type="text" id="credit-card" name="credit-card" onfocu ...

Unable to loop through a list in JavaScript

<script type="text/javascript"> window.onload = function () { for (var i=0;i<@Model.listsinfo.Count;i++) { $('#work').append($('<div class="col-md-3" id="temp"><label for="tex ...