Make sure that the TextBox OnTextChanged event in ASP.NET triggers a "setTimeout" function before the OnClick event is fired

Imagine the following situation:

<asp:TextBox ID="txt" runat="server" AutoPostBack="true" OnTextChanged="txt_TextChanged"></asp:TextBox>
<asp:Button ID="btn" runat="server" OnClick="btn_Click" CausesValidation="false" UseSubmitBehavior="false" />

when displayed, those two controls turn into:

<input name="txt" type="text" onchange="javascript:setTimeout('__doPostBack(\'txt\',\'\')', 0)" onkeypress="if (WebForm_TextBoxKeyHandler(event) == false) return false;" id="txt">
<input type="button" name="btn" onclick="javascript:__doPostBack('btn','')" id="btn">

thanks to setTimeout, the Click event is triggered before the Change event.

During my investigation, I found out that ASP.NET does this due to an old issue in some outdated versions of IE.

Nevertheless, this poses issues because when my button click conceals the textbox, it leads to some "Invalid postback or callback" errors.

How can I adjust the sequence of events so that TextChanged always occurs prior to Click?

PS: I am open to utilizing Javascript/jQuery to modify one of the events, but I have concerns about the performance implications of these solutions (as I might need to use eval).

Answer №1

After some creative problem-solving, I managed to come up with a workaround. However, I am still open to hearing better solutions from anyone who might have one.
Currently, I have implemented this function to run on page load:

function removeSetTimeout() {
    var inputs = "select, input[type=text], input[type=number], input[type=date], input[type=time]";
    $(inputs).each(function (index, elem) {
        var change = $(elem).attr('onchange');
        if (change) {
            var patch = /setTimeout\('__doPostBack\(\\'.*?\\',\\'\\'\)', 0\)/.exec(change);
            if (patch) {
                change = change.replace(patch[0], patch[0].substring(12, patch[0].length - 5).replace(/\\/g, ''));
                $(elem).attr('onchange', change);
            }
        }
    });
}

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

Unlocking the potential of Node.js: Mastering the art of passing extra parameters in async

Exploring JavaScript and Node.js I'm currently working on developing some javascript / node.js code with a specific purpose in mind: To retrieve keys from a redis database and extract relevant information from the hash. Here is an example of what ...

"React issue: Troubleshooting problems with using .map method on arrays of

I am struggling with the following code: const displayData = (data) => { console.log(data);// this displays an array of objects if (!data.length) return null; return data.map((movie, index)=>{ <div key={index} className=&qu ...

Structuring a Javascript project with a focus on component-based architecture

If I am following a component-based architecture and defining each component as an ES6 module, I organize all components in a /components folder. This folder is further divided into subfolders for grouped components. /js /components - header - ...

Sorting arrays can yield varying results depending on the browser being used

The variations in output between Chrome 70.0, Chrome 69.0, and Firefox 63.0 for the same code are puzzling. var arr = [1,2,43,1233,5546,33,6,11]; arr.sort(() => -1); //[11, 6, 33, 5546, 1233, 43, 2, 1] arr.sort(() => 1); //[1, 2, 43, 1233, 5546, 33, ...

Leveraging jQuery to Avoid Memory Leaks

After utilizing jQuery for a couple of months and delving into Javascript memory leaks for several days, I have two concerns related to memory leaks and jQuery: When I bind events (using .bind()) in jQuery, do I need to unbind them (.unbind()) before l ...

Include backing for the trial syntax 'classProperties' within an npm module

I am facing a challenge while trying to publish an npm package containing some functions for my create-react-app project. The functions work fine when I import them from the js file within the create-react-app project, but I encounter an error once I insta ...

Setting the physical path for file uploads in Asp.Net: A step-by-step guide

I need help uploading a file to a specific physical path, such as E:\Project\Folders. After searching online, I found the following code snippet: //check to make sure a file is selected if (FileUpload1.HasFile) { //create the path to save t ...

Is there a way to access the result variable outside of the lambda function?

My goal is to retrieve data from an external API using Typescript. Below is the function I have written: export class BarChartcomponent implements OnInit{ public chart: any; data: any = []; constructor(private service:PostService) { } ngOnInit( ...

What is the best way to ensure that the maximum price is mandatory when entering a minimum price?

Essentially, the process works like this: if a person inputs a minimum price but forgets to input a maximum price, then presses search, it will not perform the search and a message will appear next to the max price field reminding them to enter a maximum ...

What steps can I take to ensure my customized tab component can successfully pass an index to its children and effectively hide panes?

I'm currently working on developing a custom Tabs component to enhance my knowledge of React, but I seem to have hit a roadblock. The structure involves three key components that draw inspiration from Material-UI tabs: Tabs, Tab, and TabPane. Tabs.j ...

Encountering an error message of "Cannot POST" while trying to send data through a REST client application

Upon my attempt to add a new entry into the Doctors database I created, I encountered an error that has left me perplexed. This is how my server.js file appears: const express = require('express'); const bodyParser = require('body-parser&a ...

Ways to convert field data to lowercase in MongoDB query result

I have two Objects in my database collection. [ {"_id" : 1, name: "notLowercased"}, {"_id" : 2, name: "lowercased"}, ] Using find and $regex to search for names that include a specific string. data = await Catal ...

Can you explain the significance of the colon in this context?

Upon reviewing some SearchKit code snippets (composed with react/jsx and es2015), I came across the following line in a jsx file: const source:any = _.extend({}, result._source, result.highlight) I am curious about the purpose or significance of the colo ...

What is the ideal usage of promises in ES6 node projects?

The official bluebird promises page suggests that when using node.js, there may not be a need to manually write promises. Recently, while working on a new project, I noticed that my code heavily relies on promises. For instance, I have a databaseConnector ...

Can the text color in Grid View columns be customized according to the search item entered?

Please note: The need for changes in various columns will depend on the search request. ...

Combine strings in an array of objects

I have an array containing objects with a "Closed" property that holds numerical values. I want to loop through the array and concatenate all the "Closed" property values found in each object. For example, in the given array, the final result should be 12 ...

Loop through an object with only one array using JavaScript

I have a specific object structure that I am trying to iterate through in order to find a particular value within the array. For example, I want to check if the user name is equal to user2. While I was able to accomplish this with two separate objects (cre ...

Retrieving all buttons from a webpage and removing those with a specific background-image using JavaScript

Hey everyone, I'm still learning about javascript and other web development languages. My current task is to locate all the buttons on a webpage and remove the ones that have a specific background image. I know about using getElementsByTagName but n ...

Looking for a way to dynamically append a child element within another child

Struggling to include a new child within a specific child in Json myObject:any[] = []; this.myObject = { "type": "object", "properties": { "first_name": { "type": "string" }, "last_name": { "type": "string" }, } } addF ...

How can one obtain a distinct identifier retroactively?

One thing that I am working on is changing button images upon clicking, but this isn't the main issue at hand. Each button corresponds to unique information retrieved from the database, and when clicked, the button should change and send the appropria ...