Causing auto post back by typing text into TextBox without pressing enter or tab

回眸只為那壹抹淺笑 提交于 2019-12-25 10:00:55

问题


I want my asp.net TextBox to cause auto postback and activate a sever side event upon typing text into the TextBox without pressing enter or tab, similar to WinForms. Is this possible? If so is it possible to have this happen only after typing a certain number of characters such as three or four? Thank you.


回答1:


You cannot compare Windows-Applications and WebApplications. To post back to server when the user enters a char means that all HTML must be recreated from ASP.NET and send back to the client. But here is an example:

aspx:

<script type="text/javascript">
   var MIN_TEXTLENGTH = 3;

   function checkPostback(ctrl) {
     if (ctrl != null && ctrl.value && ctrl.value.length >= MIN_TEXTLENGTH) {
         __doPostBack(ctrl.id, '');
     }
   }
</script>


<asp:TextBox ID="TextBox1" OnKeyUp="checkPostback(this);" AutoPostBack="true" OnTextChanged="TextChanged" runat="server"></asp:TextBox>

Codebehind:

Protected Sub TextChanged(ByVal sender As Object, ByVal e As EventArgs)
    TextBox1.Attributes.Add("onfocus", "javascript:this.value=this.value;")
    TextBox1.Focus()
End Sub



回答2:


TextChange event of TextBox would become blur event in JavaScript. This means that it can fire a post back, only when you leave the control (TextBox which in client-side is an input or textarea) and the value is changed. So, that's not possible without tricks.

However, about your architecture (the way you want to post back the information to the server), I gotta say that it won't work buddy. Post backs are really expensive and you should avoid them as much as possible. My suggestion is to use ajax combined with keydown event of the input box.




回答3:


You could do this using Ajax & the onkeypress event plus some sort of counter.

So you wire a function to the onKeyPress event of your textarea, which increments a counter each time it fires, when this number gets to 3 or 4, you cal an ajax function which posts the form to the server in the background and then reset the counter again.

This will cause the form to be posted in the background for every 3rd or 4th keypress that happens while the textarea is in use, which is every keypress - space, enter, backspace etc...




回答4:


This seems like a bad idea, but...

Wouldn't you just have some java script that reads in key presses, and then initiates a post when a certain char limit was reached?

Key Press Event with Ajax or simply submit should work.

-- Seems like another poster beat me to the punch.



来源:https://stackoverflow.com/questions/6595357/causing-auto-post-back-by-typing-text-into-textbox-without-pressing-enter-or-tab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!