I was recently debugging an issue with a form where the user wanted the "enter" button when pressed in a textbox to trigger a specific ASP.NET button to postback to the server. I have done similar things in the past with a method that changes for the pressing of Character 13 which is the enter key, then finding the buttion by id and then continuing on. Well recently I found out that depending on the structure you can still get some "interesting" results. So I went looking for a different method, and came up with the following.
<script type="text/javascript">
function checkEnterSearch(e) {
var characterCode
e = event;
characterCode = e.keyCode;
if (characterCode == 13) {
//Action Goes Here
<%= Page.ClientScript.GetPostBackEventReference(YourControl, "") %>
return false;
}
else {
return true;
</script>
With this script block in your code you can simply make two modifications. Replace the "YourControl" piece with the server side name of your target control, and then add the following attribute definition to all textboxes that you want to have this behavior.
onkeypress="return checkEnterSearch(event);"
This route uses the server side operation "GetPostBackEventReference" which returns essentially a fully executable line of JavaScript that will trigger a postback with the defined target control.
I hope this helps, feel free to share comments/questions below.
This is a great solution. However, wouldn't it make sense to make this a page event, not attatched to a specific form control?
Chad,Potentially depending on your needs. In my example it was a single form field that pressing enter should cause the trigger. Any other field should not have that behavior!
Name (required)
Email (required)
Website
Notify me of followup comments via e-mail
Content provided in this blog is provided "AS-IS" and the information should be used at your own discretion. The thoughts and opinions expressed are the personal thoughts of Mitchel Sellers and do not reflect the opinions of his employer.
Subscribe To Blog RSS Subscribe To Blog Updates by E-Mail * Add to Technorati Favorites
Click here for advertising information.
Content in this blog is copyright protected. Re-publishing on other websites is allowed as long as proper credit and backlink to the article is provided. Any other re-publishing or distribution of this content is prohibited without written permission from Mitchel Sellers.