ASP.net – Using enter key in a textbox to trigger a button event as well as set focus and select text in the text box
Ok, that’s probably the longest post title I’ve used yet.
Here’s what I’m working with: a form with a textbox a button and a listbox. Users enter text into the textbox and hit the button to search for information which is returned into the listbox.
The first issue was I don’t want to have to click the search button to start the search. I wanted to be able to just hit enter after typing text. The button triggers vb code behind the page to do the search.
So I found adding the following to the Page_Load sub-routine allowed me to hit enter in the textbox which triggers the button code:
txtSearch.Attributes.Add(“onkeypress”, “return clickButton(event,'” + btnSearch.ClientID + “‘)”)
Replace txtSearch with the id of your textbox and replace btnSearch with the id of your button.
Next, I wanted the text in the textbox to be highlighted/selected after performing a search so you could turn around and type something else and do another search without touching the mouse.
This is accomplished by adding the following to the Page_Load sub-routine:
Me.txtSearch.Focus()
txtSearch.Attributes.Add(“onfocus”, “JavaScript:document.getElementById(‘” + txtSearch.ClientID + “‘).select();”)
Replace txtSearch with the id of your textbox.
Note: Sometimes when you copy and paste code like that above the quotes and or apostrophes can get funky and need to be corrected.