Connect the grid view to the text box by binding the onkeypress event

I currently have a gridview that updates based on the number entered in a textbox using the OnTextChanged event. The issue is that the gridview only refreshes when the textbox loses focus, but I want it to update as soon as a key is pressed while entering the number. I've tried various methods like an ajax call to a web method or calling a code behind function from JavaScript, but nothing has worked.

Here is the input textbox:

<asp:UpdatePanel runat="server" ID="upNumComps" UpdateMode="Conditional">
    <ContentTemplate>
        <table>
            <tr>
                <td>
                    <asp:Label ID="lblNumComps" runat="server" Text="Nº de Componentes " ForeColor="#142658" Style="font-weight: bold;"></asp:Label><span style="color: red; margin-right: 5px;"> * </span>
                </td>
                <td>
                    <asp:TextBox ID="txtNumComps" runat="server" AutoPostBack="True" OnTextChanged="txtNumComps_TextChanged"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="rfvNumComps" runat="server" ForeColor="red" ControlToValidate="txtNumComps" ErrorMessage=""></asp:RequiredFieldValidator>
                </td>
            </tr>
        </table>
    </ContentTemplate>
</asp:UpdatePanel>

And here is the gridview:

<asp:UpdatePanel ID="upDetComps" CssClass="mGrid1" runat="server">
    <ContentTemplate>
        <asp:GridView ID="grvComponentes" runat="server" AutoGenerateColumns="False" ForeColor="#001f3f" GridLines="None" Style="text-align: center;">
            <Columns>
                <asp:TemplateField HeaderText="Nº" ItemStyle-HorizontalAlign="Center">

                    <ItemTemplate>
                        <asp:Label ID="lblRowNumber" Text='<%# Container.DataItemIndex + 1 %>' runat="server" Style="margin-left: 10px; margin-right: 10px;" />
                    </ItemTemplate>
                </asp:TemplateField>

                <asp:TemplateField HeaderText="Componente">
                    <ItemTemplate>
                        <asp:TextBox ID="txtComponente" runat="server" Style="margin-left: 10px; margin-right: 10px; margin-top: 5px;"></asp:TextBox>
                        <asp:RequiredFieldValidator ID="rfvComponente" ForeColor="red" runat="server" ControlToValidate="txtComponente" ErrorMessage="*"></asp:RequiredFieldValidator>
                    </ItemTemplate>
                </asp:TemplateField>

                <asp:TemplateField HeaderText="Base">
                    <ItemTemplate>
                        <asp:TextBox ID="txtBase" runat="server" Style="margin-left: 10px; margin-right: 10px; margin-top: 5px;"></asp:TextBox>
                        <asp:RequiredFieldValidator ID="rfvBase" ForeColor="red" runat="server" ControlToValidate="txtBase" ErrorMessage="*"></asp:RequiredFieldValidator>
                    </ItemTemplate>
                </asp:TemplateField>

                <asp:TemplateField HeaderText="Comprimento">
                    <ItemTemplate>

                        <asp:UpdatePanel runat="server">
                            <ContentTemplate>

                                <asp:TextBox ID="txtComprimento" runat="server" AutoPostBack="true" OnTextChanged="txtComprimento_TextChanged" Style="margin-left: 10px; margin-right: 10px; margin-top: 5px;"></asp:TextBox>
                                <asp:RequiredFieldValidator ID="rfvComprimento" ForeColor="red" runat="server" ControlToValidate="txtComprimento" ErrorMessage="*"></asp:RequiredFieldValidator>

                            </ContentTemplate>
                            <Triggers>
                                <asp:AsyncPostBackTrigger ControlID="txtComprimento" EventName="TextChanged" />
                            </Triggers>
                        </asp:UpdatePanel>

                    </ItemTemplate>
                </asp:TemplateField>

            </Columns>
        </asp:GridView>
    </ContentTemplate>
</asp:UpdatePanel>

Code Behind function

protected void txtNumComps_TextChanged(object sender, EventArgs e)
{
    string rowCount = "";
    if (!CheckInt(txtNumComps.Text) || txtNumComps.Text == "0")
    {
        txtNumComps.Text = "";
        txtNumComps.Attributes.Add("placeholder", "Insira um número");
        rowCount = "0";
        ViewState["rowCount"] = rowCount;
        grvComponentesBind();
    }
    else if (CheckInt(txtNumComps.Text) && txtNumComps.Text != "0")
    {
        rowCount = txtNumComps.Text;
        ViewState["rowCount"] = rowCount;
        grvComponentesBind();
    }
}

EDIT

Here's what I've done so far:

I added this JavaScript function

 <script type="text/javascript">
    function RefreshUpdatePanel(id) {
        debugger
        __doPostBack(id, '');
        document.getElementById(id).blur(id);
        document.getElementById(id).focus(id);
    };
</script>

Then, I updated the textbox to include this script:

<asp:TextBox ID="txtNumComps" runat="server" onkeyup="RefreshUpdatePanel(this.id);" OnTextChanged="txtNumComps_TextChanged"></asp:TextBox>

Although now the gridview updates with each keypress in the textbox instead of waiting for a focus change, there still remains an issue. The textbox loses focus after one key press, and attempting to set the focus programmatically did not work or caused the cursor position to shift back to the previously entered number.

Answer №1

It's unclear why one would choose to manage it in such a manner, but I guess it is possible to execute the following code:

txtNumComps.Attributes.Add("onKeyUp", "document.Form1.submit();");

However, this could potentially be bothersome for many users...

Answer №2

To trigger the TextChanged event, you can attach a custom keyup event to the textbox. Within this event, simply set focus to another element and the event will be fired.

<asp:TextBox ID="txtNumComps" runat="server" AutoPostBack="True" OnTextChanged="txtNumComps_TextChanged"></asp:TextBox>

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

<script type="text/javascript">
    $(document).ready(function () {
        $('#<%= txtNumComps.ClientID %>').keyup(function () {
            $('#<%= TextBox1.ClientID %>').focus();
        });
    });
</script>

One thing to consider is that with this method, if a user types something like 12, there will be an unnecessary PostBack.

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

Encountering excessive re-renders while using MUI and styled components

Hey there! I recently worked on a project where I used MUI (Material-UI) and styled-components to render a webpage. To ensure responsiveness, I made use of the useTheme and useMediaQuery hooks in my web application. My goal was to adjust the font size for ...

Tips for transforming HTML to a dynatable or datatable

I have a PHP page that returns HTML table data. I’m looking to convert this table into either DataTable or Dynatable. I’ve attempted to include the necessary files (JavaScript and CSS) in the page where the PHP script generates the table. In my JavaScr ...

Exploring the functionality of event.target.name.value

I've been struggling to make event.target.name.value work for an input field in my form. When I submit the form, the values appear as null and I have to click twice to get them. This is the code I've written: const [name, setName] = useState(& ...

Symfony: The Database Query Button with a Pop-up Feature

I am looking to create a button that will automatically search my database for all users with a "secouriste" attribute set and display their first name, last name, and phone number in a popup. After conducting research, here is what I have gathered: In m ...

Firefox throwing up errors with Cross-Domain Ajax Requests

I recently encountered an issue with a cross domain ajaxSubmit function in one of my views. $(".FileUploadDiv form").first().ajaxSubmit({ success: function (success) { var redirectUrl = "@(Url.Action("CreateRfp"))"; location.href = red ...

Utilizing jQuery to send AJAX requests and display the results on separate lines within a textarea

My form includes a text area where users can enter keywords, one per line. I would like to implement the following functionality: upon clicking a button, an ajax request will be sent to the server to retrieve the result for each keyword entered. The resul ...

Protractor: Saving data locally with local storage - A step-by-step guide

I've come across several instances of retrieving previously saved information, but I haven't found any examples of retrieving stored values. ...

jQuery error: an unexpected token was encountered

I am encountering an issue with an "unexpected token =" error on the line toggleNav = function(evt){ in the code snippet below. Despite going through various similar posts, I am unable to pinpoint why this error is occurring. Any assistance in guiding me ...

Delay the execution of Javascript code for one hour daily over the course of a month

Updated Question: Despite the larger issue, can someone explain why the sleep function in the code below doesn't provide a one-hour pause in execution? Understanding this would be greatly appreciated. I am trying to trigger a JavaScript function that ...

Utilizing Windows Azure Website alongside static HTML stored in Blob storage

Currently, I have a .NET MVC application deployed on an Azure Website to serve static HTML pages stored in a blob container when clicking on a corresponding link. My inquiries are as follows: When accessing a blob in Azure, the standard URL format is . ...

Problem occurs when tab links vanish after clicking on another part of the website

Exploring the world of Javascript as a newcomer has been quite an adventure, but I've encountered a hurdle with tab links on my website. Everything seems to be working fine – the links cycle through and display the correct content. However, when it ...

What is the best way to obtain a virtual in mongoose when a property is excluded?

Imagine I have a post Model with fields like UserId, Title, Desc, and a likes array which references UserIds. When querying, I have a virtual property to calculate the number of likes a post has: schema.virtual("numLikes").get(function () { return this. ...

Adding a tooltip to a specific header in a Vue list - here's how!

My goal is to add a tooltip to a specific header labeled 'Retire' within a data table, without affecting any of the other headers. It's been quite the learning experience for me as a Vue novice, but with the help of AI (chatgpt), I've m ...

"Enhance your data visualization with Highcharts Windbarb and effortless AJAX data

Alright. Let's rephrase a question that hasn't been answered yet. I've got a chart below with data loading dynamically via ajax. A simplified version (without ajax) of this graph works well as shown in this jsfiddle. The code below represe ...

Ways to deactivate an individual menu option?

Here I am with another query related to Webix. I am attempting to deactivate a single menu item, but the onItemClick function for the submenu is still active. Check out my code snippet below: webix.ui({ view:"menu", id:'menu', data:[ ...

Modifying Selectize Ajax data in real-time

How can the student_id be changed each time the modal is opened? This is the code: $('#relationshipModal input[name=existing_user]').selectize({ valueField: 'id', searchField: 'name', options: [], create: fal ...

I am interested in updating the content on the page seamlessly using Angular 6 without the need to reload

As a newcomer to Angular, I am interested in dynamically changing the page content or displaying a new component with fresh information. My website currently features cards, which you can view by following this Cards link. I would like to update the page ...

retrieving the selected checkbox value

My challenge is to extract the values of dynamically changing checked checkBoxes on my webpage. For example: while ($row=myqli_fetch_array($result)){ echo"<div>"; echo"<select id=\"course\" onchange=getCheckBox()> <opt ...

I receive an [object HTMLCollection] as the output

I am currently working on recreating a login page and I want it so that when the button is clicked, it displays the name you entered, but instead, it returns [object HTMLCollection]. My expectation was to have the name displayed as entered. var nombre ...

Utilizing dual functions within the onChange event handler in React

I have a situation where I need to pass a function from a parent component to a child component through the onChange event, as well as another function in the child component to update its own state. How can I achieve this? Parent export function Fruits() ...