Enter key causes the unnecessary post-back

坚强是说给别人听的谎言 提交于 2019-12-25 04:37:19

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!