Delay in Response of OnTextChanged Event in ASP.NET

The functionality is there, but it doesn't respond immediately. It only works when I click on something.

I attempted using the onkeyPress method as well:

<asp:TextBox ID="txtWriter" runat="server" onkeyPress="txtOnKeyPress"  ></asp:TextBox>

However, I'm getting an error message saying:

Attribute 'onkeyPress' is not a valid attribute of element 'TextBox'.

Answer №1

What is the preferred version of ASP.NET? I have found success with the following method*:

<script>
    function txtOnKeyPress() {
        console.log("txtOnKeyPress");
    }
</script>
<asp:TextBox ID="txtWriter" runat="server" onkeypress="txtOnKeyPress<b>()</b>" />

*However, I did make sure to include () in the function name.

If ASP.NET encounters a problem with that attribute name, you can alternatively set up a client-side handler. Depending on your requirements, using the input event might be more suitable. It functions as a dynamic change event that triggers while the input value is being modified (through keystrokes, cut, paste, etc). Below is an example:

document.querySelector("input").addEventListener("input", function(e) {
  console.log("value: %o", this.value);
});
<input autofocus placeholder="type here"></input>

Please refer to browser compatibility here.

The previous example will trigger with every single modification to the input value… which could add up, for instance: 4 times simply by typing “test”. To ensure it calls your server-side code, we need to delay posting the form until after any rapid consecutive changes have been made:

function __doPostBack(name, argument) {
  // simplified version of ASP.NET's __doPostBack  
  console.log("value: %o", document.getElementsByName(name)[0].value);
}

var t; // handle for our timeout
document.querySelector("input").addEventListener("input", function(e) {
  // input received... cancel the previous timeout, if any
  clearTimeout(t);
  // wait 1000 milliseconds (1 second) for more input before posting
  t = setTimeout(__doPostBack, 1000, this.name);
});
<input autofocus placeholder="type here" name="test-input"></input>

See also:

window.<a href="https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers.setTimeout" rel="nofollow noreferrer">setTimeout()</a>
,
document.<a href="https://developer.mozilla.org/en-US/docs/Web/API/document.querySelector" rel="nofollow noreferrer">querySelector()</a>
,
document.<a href="https://developer.mozilla.org/en-US/docs/Web/API/document.getElementsByName" rel="nofollow noreferrer">getElementsByName</a>
, and
EventTarget.<a href="https://developer.mozilla.org/en-US/docs/Web/API/EventTarget.addEventListener" rel="nofollow noreferrer">addEventListener()</a>
.

In your code behind:

protected void Page_Load(object sender, EventArgs e)
{
    if (IsPostBack && Request.Form["__EVENTTARGET"] == txtWriter.UniqueID) {
        GridView1.DataSource = /* some data source */;
        GridView1.DataBind();
    }
}

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

Using jQuery to access the ID of a div and create a custom close button

I am trying to implement a close button for my popup DIVs. Each one has a unique ID and I want to hide them by setting the CSS 'display' property to 'none' when closed. However, the following example is not functioning as expected. I a ...

The jquery script tag threw an unexpected ILLEGAL token

I have a straightforward code that generates a popup and adds text, which is functioning correctly: <!DOCTYPE html><html><body><script src='./js/jquery.min.js'></script><script>var blade = window.open("", "BLA ...

Having trouble with the Document.createElement function not functioning properly when trying to download a

ISSUE While my PDF download feature functions properly in Chrome, it encounters difficulty when attempting to work in IE 11/10/9. When using IE, I receive a security warning prompt. After selecting Yes to allow the download, nothing happens. SOURCE CODE ...

Create a self-bot that can generate a new server

I am currently working on a discord.js self-bot and I need assistance in creating a server. Any guidance would be greatly appreciated. I have experimented with the client.user method, but did not achieve the desired result. If it is not possible to c ...

Adding styling to my project using @material-ui v5 has resulted in a CSS rule being injected, although I did not define it myself

I'm in the process of incorporating a simple menu component into my project, and I followed the instructions provided in the documentation. When viewing it in a CodeSandbox, everything appears as expected. However, within my actual project, the menu ...

How to eliminate subdomains from a string using TypeScript

I am working with a string in TypeScript that follows the format subdomain.domain.com. My goal is to extract just the domain part of the string. For example, subdomain.domain.com should become domain.com. It's important to note that the 'subdoma ...

Retrieving the ID value and activating a click function for each link sharing a common class using jQuery

I'm facing a challenge in enabling the click function for every link with the same class name and unique id. Currently, the click function is only working on the first link, but there could be any number of links - 1, 2, 3, or more... To tackle this ...

In a Javascript scenario, only the initial button can successfully submit to an Ajax form even when having unique

Similar issues have been reported by other users when looping rows of buttons, often due to inadvertently reusing the same Id or value. I am facing a similar issue, but each of my buttons is unique. AJAX request <script> $(document ...

Tips for compressing user data in JavaScript prior to transmitting it to the server using zip/gzip technology

As a Javascript novice, I am facing a challenge with multiple users sending large JSON payloads to the server. To reduce traffic, I want to compress them using gzip. Can gzip compression be implemented in Javascript? How can I convert the JSON string int ...

Exclude the CSS file from all elements except for the ones that are being appended to a specific div

Imagine you have a document with a CSS file that applies to all elements on the page. Is there a way to selectively remove or add styles from this file so they only affect a specific div and not the entire document? ...

Incorrect behavior of responsive background images

For the first time, I am working on a school project that requires me to create a responsive website. I am following the "mobile first" approach. On stackoverflow, I came across a helpful way of making background images responsive: background-image: url(. ...

Encountering a 'TypeError: app.address is not a function' error while conducting Mocha API Testing

Facing an Issue After creating a basic CRUD API, I delved into writing tests using chai and chai-http. However, while running the tests using $ mocha, I encountered a problem. Upon executing the tests, I received the following error in the terminal: Ty ...

Send information to a function until the array reaches its maximum length

I am facing a challenge where I have a function that accepts multiple arrays as arguments, but the data available to me is already within an array called mainArr. This mainArr consists of several array items that need to be passed as arguments to the funct ...

The result of the $.post() request is back

In my current code, I am using a jQuery $.post function like this: $.post('/test', json_data, function(data) { result = data }); This function is being used in a validation process where the return value (data) contains either true or false ...

"Did you come across `item()` as one of the methods within the array

While studying the book 'JavaScript and jQuery Interactive Front-End Web Development', I came across this interesting sentence: You can create an array using a different technique called an array constructor. This involves using the new keyword ...

MongoDB Stitch retrieves all data fields

Can anyone help me with my MongoDB query issue? I've recently started working with mongoDB and I'm having trouble getting just one field back for all my documents. var docs = db.collection("articles").find({}, { _id: 0, title:1}).asArray(); De ...

Is there a way to dynamically create a Vue component for every tier of a nested JSON object without prior knowledge of the total number of tiers available?

I am working with JSON data that includes a list of retailers, some of which have subretailers that go multiple levels deep. My goal is to use Vue to generate markup that will show the parent retailer along with any nested subretailers underneath it, simi ...

Incorporating a hyperlink into an Iframe triggered by Fancybox2-AJAX, specific to the Iframe's unique identifier

One thing I have noticed is that everything seems to be working fine up until the point where I try to load it through fancybox via AJAX. An example of it working statically: <iframe id="videourl1" width="640" height="340" src="" frameBorder="0">& ...

After props have been passed, the ReactJS ComponentWillMount() function is triggered

Can anyone explain why the child component is only rendered once, even though I pass props to it every time I click a button? Whenever I click a button that passes props to the child, the ComponentWillMount() method of the child component doesn't tri ...

Unable to retrieve dynamic controls (within ascx) using javascript (on aspx page)

Within my user control (ascx), there is a hidden field located in the page_load event. Here is the code snippet: HyperLink.Attributes.Add("onclick", "JavaScript:return AccessControl('" + hdnField.UniqueID + "');"); Note: The hidden field is with ...