Makara
Makara

Reputation: 233

How to handle keydown Event in asp.net Textbox?

I have a textbox in web form(asp.net). when user already keyin data, then they will press Enter key, so that the data will be update to database.

Is there any way possible to perform this?

Upvotes: 1

Views: 2460

Answers (2)

Boriss Pavlovs
Boriss Pavlovs

Reputation: 1441

function InitTextBox() {
//var _txt = $('#<%= txt.ClientID%>'); or
var _txt = $('input:[id*="txtId"]');
if (_txt.length < 1) return;
_txt.get(0).autocomplete = 'off';
_txt.on('keydown', function (evt) {
    var _self = $(this);
    event = evt ? evt : window.event;
    if (event.keyCode == 13) {
        if ($.browser.msie)
        { event.cancelBubble = true; event.returnValue = false; }
        else { event.preventDefault(); }
        if (_self.val().length > 0 && _self.val().match(/^\s*$/) == null)
            __doPostBack(_self.attr('name'), '');
    }
});
}
Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(InitTextBox);

And set autopostback for textbox to false, please

Upvotes: 1

Brian Mains
Brian Mains

Reputation: 50728

Dino Esposito had wrote about this a while back. You wouldn't necessarily need a custom control, but can use his JavaScript.

If you have a control wrapped around a Panel, and you have the DefaultButtonID property set, the panel will trigger a postback on enter too by clicking the desired button specified by the ID. That's another way.

Upvotes: 1

Related Questions