ASP.NET/Javascript - Handling Enter click for submitting the active form.

There are some ways to do this.
The most simple way is to use the default submit button - this is by default the first button in the which performs postback (link button, image button, button). If the button you would like to use by default is not the first you can add one more button on the top of page (for example image button with 1x1 pixels picture - invisible). This guaranties that the pressing enter will cause postback independant of the browser - it works with every browser (that I know :-)).

However, we can use simple javascript code to handle the event of pressing enter button:
<body onkeydown="if(event.keyCode == 13){document.getElementById('" + ImageButton1.ClientID + "').click();}">

One more way: DataList1.Attributes.Add("onkeypress", String.Format("javascript:return WebForm_FireDefaultButton(event, '{0}')", ImageButton1.ClientID)) - this performs postback when the focus is on the datalist1. Of course we can use every control that has child controls.
But my experience shows that this doesn't work good with Firefox.

Here is also way to add javascript event dynamically:

<script type="text/javascript">
addEvent(window, 'load', function() {
document.getElementById('myfield').focus()
});

function addEvent(obj, evType, fn){
if (obj.addEventListener){
obj.addEventListener(evType, fn, true);
return true;
} else if (obj.attachEvent){
var r = obj.attachEvent("on"+evType, fn);
return r;
} else {
return false;
}
}
</script>



No comments:

Post a Comment