Difference between onkeypress and onkeydown in asp.net
I have a form with a default button set.So when i press enter,form is submitted regardless of the focus. My requirement is when focus is inside fileupload control and enter is pressed,instead of submitting the form show browse dialog. So I created a panel and attached a onKeyPr开发者_开发知识库ess event to this panel
fileUploadDocument.Attributes.Add("onkeyPress", "return ByPassEnter(event);");
<asp:Panel ID="fileUploadDocument" runat="server">
<div>
<uc2:FileUploadControl ID="ucdocxUploadControl" runat="server" ErrorMessageNoFileSelected="Please select a file for upload."
ValidationGroup="BrandLogoFileUpload" />
</div>
</asp:Panel>
function ByPassEnter(e) {
var evt = (e) ? e : window.event;
var key = (evt.keyCode) ? evt.keyCode : evt.which;
if (key == 13) {
document.getElementById('<%=ucdocxUploadControl.BaseFileUploadControl.ClientID %>').click();
CancelDefault(evt);
}
}
function CancelDefault(e) {
e.cancel = true;
if (e.preventDefault) {
e.preventDefault();
}
e.returnValue = false;
}
When i press enter on fileupload control, browse dialog shows up and when i choose a file or hit cancel on browse dialog,postback happens. e.returnValue = false should prevent the postback but even then postback happens.
However if i change onkeypress to onkeydown,everything works and postback doesnot happen.Can somebody tell me the difference in these events and why postback is happening in onkeypress.
The keypress event fires after the key is pressed and released. At that point your form's submit action is activated.
keydown fires after the press but before the release. At that point you can cancel the keypress from registering.
精彩评论