问题
I have a web-application form in vb.net. When I click on a radio button, a postback is run on the server. If I press enter at the same time it causes another postback to the server. How do I prevent that second postback?
<td class="tdClassic" id="tdCT">
<asp:RadioButton ID="rbSingle" runat="server" Text="Singl" AutoPostBack="true" GroupName="grpT" />
<asp:RadioButton ID="rbMultiple" runat="server" Text="Multiple" AutoPostBack="true" GroupName="grpTrainer" />
</td>
回答1:
If you are using jQuery you can stop the endter key from submitting the form using:
$(document).keypress(function(e)
{
if(e.keyCode === 13)
{
e.preventDefault();
return false;
}
});
if not this might work:
<script language="JavaScript">
var nav = window.Event ? true : false;
if (nav) {
window.captureEvents(Event.KEYDOWN);
window.onkeydown = NetscapeEventHandler_KeyDown;
} else {
document.onkeydown = MicrosoftEventHandler_KeyDown;
}
function NetscapeEventHandler_KeyDown(e) {
if (e.which == 13 && e.target.type != 'textarea' && e.target.type != 'submit') {
return false;
}
return true;
}
function MicrosoftEventHandler_KeyDown() {
if (event.keyCode == 13 && event.srcElement.type != 'textarea' &&
event.srcElement.type!= 'submit')
return false;
return true;
}
</script>
or if you have a button on the page then UseSubmitBehavior
might be a better solution:
<asp:button id="Button1" text="Submit" onclick="SubmitBtn_Click" usesubmitbehavior="false" runat="server"/>
see https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.button.usesubmitbehavior.aspx
来源:https://stackoverflow.com/questions/30210338/enter-key-causes-the-unnecessary-post-back