Setting the default button for a textbox in ASP. NET

Source: Internet
Author: User
Hitting the Enter key in a textbox can sometimes have undesired effects like the wrong submit button being "clicked". the method described below allows you to specify a default button to submit when the user hits the Enter key in a textbox.

When you press a key on your keyboard, the JS onkeypress event is fired. this calla function to which we pass the ID of the button associated with the textbox. the function gets a reference to the button and simuilates a mouse-click on the button. we perform a browser detection because IE and Netscape have different event models. the function finally returns false so that the keypress event is canceled (otherwise a second form submit will be raised ). this works with newer versions of IE/Netscape.

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;

}

}

}

// Code behind
Textbox1.attributes. Add ("onkeypress", "Return clickbutton (event, '" + button1.clientid + "')");

The code behind generates the following code:

<Input name = "textbox1" type = "text" id = "textbox1" onkeypress = "Return clickbutton (event, 'button1')"/>

This causes web control button1 to be clicked when the Enter key is hit inside textbox1.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.