How to call postback using javascript on ASP.NET form

I have a web form with textbox and button. I want after “ENTER” key click on textbox postbak form.

I am using next code:

onkeypress=" if(event.keyCode==13)
 { alert(2);
WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions('ctl00$ContentPlaceHolder1$btnSearch', '', true, '', '', false, false));
alert(2); 
return false;}

where WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions('ctl00$ContentPlaceHolder1$btnSearch', '', true, '', '', false, false));

is javascript code for button event onclick.

I get two alerts, but postback doesnot happen.

Any ideas what is wrong?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

ASP.NET already creates a client side javascript method __doPostBack to support postback.

Example: __doPostBack('__Page', 'MyCustomArgument');

Method 2

Easier way of doing it is to enclose the controls in a panel and use defaultbutton attribute on the panel, like this:

<asp:Panel ID="pan1" runat="server" DefaultButton="btnSave">
    <asp:TextBox ID="txt1" runat="server" />
    <asp:Button ID="btnSave" runat="server" />
</asp:Panel>

Then when you press ‘enter’ after entering the value in the text box it will behave as if you clicked on the btnSave button.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x