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();
}
}