简体   繁体   中英

Resetting textbox text via javascript

function clickButton(e, buttonid)         
            var evt = e ? e : window.event;
            var bt = document.getElementById(buttonid);
            if (bt) {
                if (evt.keyCode == 13) {
                    bt.click();                                                  
                    return false;
                }
            }
        }

txtChatMessage.Attributes.Add("onkeypress", "return clickButton(event,'" + btnSendChat.ClientID + "')");

this function is an attribute that is set in code behind file. How do I reset the text in textbox after the button click fires

You can do it like this, by passing the text field from code behind using this , and setting its value to empty string in javascript

In code behind

txtChatMessage.Attributes.Add("onkeypress", "return clickButton(this, event,'" + btnSendChat.ClientID + "')");

In javascript

function clickButton(txt, e, buttonid){
   var evt = e ? e : window.event;
   var bt = document.getElementById(buttonid);
   if (bt) {
        if (evt.keyCode == 13) {
             bt.click();    
             txt.value = "";                                               
             return false;
   }

The above code will over write the existing value of text box. To save it for later use we can use hidden field

In html

<asp:hidden id="hdnText" runat="server" >

In javascript

function clickButton(txt, e, buttonid){
   var evt = e ? e : window.event;
   var bt = document.getElementById(buttonid);
   if (bt) {
        if (evt.keyCode == 13) {
             bt.click();    
             document.getElementById('<%= hdnText.ClientID %>').value = txt.value;                                               
             return false;
   }

In Code behind

Send text field to javascript function

txtChatMessage.Attributes.Add("onkeypress", "return clickButton(this, event,'" + btnSendChat.ClientID + "')");

Get value of textbox from hidden field

string textBoxValue = hdnText.Value;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM