Canceling the default submit button in ASP.NET - asp.net

I have an ASP.NET application where there's a few ASP.NET buttons and several plain HTML buttons. Anytime there's a textbox where a user hits enter, the ASP.NET button tries to submit the form.
I know I can change the defaultButton, but I don't want there to be any default button. I just want it so when the user presses enter it doesn't do anything.
I've tried setting defaultButton to blank, but that doesn't seem to work. How do I prevent the form from being submitted by the ASP.NET button when enter is pressed?

You can set the button's UseSubmitBehavior = false
btnCategory.UseSubmitBehavior = false;

Here is what I used to fix this problem.
<form runat="server" defaultbutton="DoNothing">
<asp:Button ID="DoNothing" runat="server" Enabled="false" style="display: none;" />

I also had this problem with an ImageButton on my MasterPage (the Logout button) being set as the default button (so whenever someone pressed Enter, it would log them out). I solved it by using the following line in the Page_Load event on every child page, which is a bit of a work-around, but it works:
Form.DefaultButton = cmdSubmit.UniqueID;
Hope this helps someone else.

<asp:TextBox ID="TXT_Quality" runat="server" Width="257px"
onkeypress="return key_Pressed(event, this);">
</asp:TextBox>
function key_Pressed(e, textarea)
{
var code = (e.keyCode ? e.keyCode : e.which);
if(code == 13)
{
return false;
}
return true;
}

Related

Display in correct order using RequiredFieldValidators, ValidatorCallout and a ModalPopupExtender of validation is OK

I'm trying to get a sequence of things to happen in the correct order, but no luck. What I have is a number of fields with asp:ReuiredFieldValidators and asp:ValidatorCallout to display validation messages. This is triggered with a button Save with validation="true".
If all validates, it should display a modal dialog asking for two choises on how to save the data. No matter the answer, it should always continue at this stage to code behind save function.The AjaxToolkit_ModalPopupExtender is connected to the same save button.
What happens is that the validation callouts and modal dialog is shown at the same time.
Searched for tips and help but haven't found any, for me, helpful! Most grateful for any help!
Cheers
/Johan
You can show the ModalPopup from codebehind(in BtnSave.Click-handler) if the page is valid:
Page.Validate("YourValidationGroup");
If(Page.IsValid){
ModalPopup1.Show();
}
Therefor you need to set the TargetControlID of the ModalPopupExtender to a hidden button:
<asp:Button ID="Hid_ShowDialog" Style="display: none" runat="server" />
You must move to Code Behind only when the Page is validated in client side. You can do it using OnClientClick of button
<asp:Button ID="ShowDialog" onClientClick = "return ValidatePage();"
runat="server" />
<script type="text/javascript">
function ValidatePage() {
if (typeof (Page_ClientValidate) == 'function') {
Page_ClientValidate();
}
if (Page_IsValid) {
// do something
alert('Page is valid!');
return true;
}
else {
// do something else
alert('Page is not valid!');
return false;
}
}
</script>

How do I associate the Enter key with a button on an ascx page?

I have a button on one of my content pages which i need to fire on hitting the enter button. I tried specifying the default button in the updatepanel but without any avail. If you have a solution for the same please let me know.
Thanks in advance.
Use the panel control and setup your button with DefaultButton="Button1"
<asp:Panel ID="Panel1" runat="server" DefaultButton="Button1">
.................................
...............your contents..................
</asp:Panel>
You can also use javascript, which you can call from the textbox's key press event,
function checkKey(b1, e) {
if (e.keyCode == 13) {
document.getElementById(b1).click();
return false;
} }
Hope this will helps...

Login by hitting enter key in asp.net Login control

I must have read a hundred forum and blogposts about this, all talking about placing a Panel and setting the Default button to the Login button, or setting the Default button in the Form. I've tried all this plus lots more, but nothing works.
I have two LinkButtons in my Login control, which is converted to a template. The first is the Login button, the second is a link to a register page. When I hit enter, the Register LinkButton fires and redirects to the register page.
I've tried setting the default button on panels and placing them everywhere and setting the default button in the Form tag itself. I tried removing the Register button and setting an onclick on the and calling a function that redirected to the register page. That didn't even work, and the enter key still redirected to the register page.
They are placed in the LayoutTemplate like this:
<div class="btn-login">
<asp:LinkButton ID="LoginButton" runat="server" CommandName="Login" ValidationGroup="LoginUserValidationGroup"
Height="38px" Width="120px">
</asp:LinkButton>
</div>
<div class="btn-opretbruger">
<asp:LinkButton ID="Register" runat="server" ValidationGroup="LoginUserValidationGroup"
Height="38px" Width="120px" PostBackUrl="/Account/registrerbruger.aspx">
</asp:LinkButton>
</div>
All the articles I have read used Button controls, and I use a LinkButton.
Any ideas?
Task 1)
Add some scrip to your page to disable the enter key...
function stopRKey(evt) {
var evt = (evt) ? evt : ((event) ? event : null);
var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
if ((evt.keyCode == 13) && (node.type == "text")) { return false; }
}
Task 2)
Add some script that allows you to target a html element and raise the event handler for it
function submitByTarget(event, target) {
if (event.keyCode == 13) {
jQuery('#' + target.id).click();
}
}
Task 3)
Add an event handler for your login txtbox that waits for the enter key to be hit and raises the correct .click handler for the target button...in this case 'login'
txtLogin.Attributes.Add("onkeypress", "return submitByTarget(event," + btnSearch.ClientID + ");");
Include the following code in the page load even.It'll automatically set the focus on the button.
//Set the default button for the Login page
this.Page.Form.DefaultButton = btnLogin.UniqueID;

enter key in asp.net firing wrong button

I have a text box and many buttons. When user is in some text box and presses the "enter" key then specific button click event is raised. I read on the internet that there are some problems with the "enter" key and I tried few solutions but still it always enters that button event (that button is the first button in the page).
I tried creating a button which does nothing and writing this in the page_load:
idTextBoxFA.Attributes.Add("onkeydown","if(event.which || event.keyCode){if ((event.which == 13) || (event.keyCode == 13)) {document.getElementBtId('" + noEnterButton.UniqueID + "').click();return false;}} else {return true}; ");
All my page controls are in a form and I tried giving the form "defaultButton" property to that button I created. That didnt work either.
Any idea why this isn't working and what am I doing wrong?
The standard way in ASP.NET to control which submit button is activated when ENTER is pressed is to wrap the controls and buttons in an asp:Panel with the DefaultButton property set to the correct button.
If I'm reading your question properly, you just want one specific button to be activated when ENTER is pressed, so wrap everything on your page in a single asp:Panel.
<asp:Panel id="pnlDefaultButton" runat="server" DefaultButton="btnOK">
<!-- All controls here including: -->
<asp:Button id="btnOK" runat="server" Text="OK" />
</asp:Panel>
No panel is needed.
Just use the following:
UseSubmitBehavior="false"
Please use
idTextBoxFA.Attributes.Add("onkeypress", "javascript:var evnt = window.event";
if(evnt.keyCode==13)
{
document.getElementById('" + noEnterButton.ClientID + "').click();
}
else{};");

TextBox causes Button Postback in ASP.NET

ASP.NET 2.0, testing in FF3 and IE7.
When I hit the 'enter' button from a text box the corresponding "OnClick" event for the first ImageButton in the page is fired. If I remove that image button, it fires the next ImageButton OnClick event on the page.
From the FireBug console, if I use JavaScript to submit the Form, this does not happen. But for whatever reason hitting enter from the textbox triggers the unrelated ImageButton event.
I found this question which had a similar problem, however the proposed answer to that solution doesn't work since ImageButtons do not have a "UseSubmitBehavior" property on them.
I don't understand why this event is firing. If I look at Request.Form, I can see that __EVENTTARGET is empty, and it is in fact posting the entire form contents (all of my textboxes), but also includes imageButton.x and imageButton.y key/value pairs.
Why is this? I suppose I could detect "enter" key presses from these text boxes with javascript, but my experience in the past is this behavior is highly variable between browsers. Any suggestions?
here's a more elegant solution
<asp:TextBox ID="TextBox1" runat="server"
onkeydown = "return (event.keyCode!=13);" >
</asp:TextBox>
read the entire post here
You could try setting a default button in an asp panel or on your form. This will let you control what happens when a user hits the enter key.
I'm having the same issue on my project.
This issue is caused because ASP.NET always will assume that the first element that inherits from IButton interface (Button and ImageButton) is the default button from the page.
Hipoteticaly, if you use an LinkButton instead of Button or ImageButton, this issue is solved.
You can find more information here on MSDN.
You can disable the Enter key from being pressed, so the user will have to click on of your ImageButtons. Just paste this javascript block onto your page:
<script type="text/javascript">
function stopRKey(evt) {
var evt = (evt) ? evt : ((event) ? event : null);
var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
if ((evt.keyCode == 13) && (node.type=="text")) {return false;}
}
document.onkeypress = stopRKey;
</script>
Recently, I've been doing more on the client with web services and fewer postbacks. By moving my controls outside of the form element (or eliminating it altogether), the problem goes away. It's inserted by default on aspx pages, but it didn't occur to me until recently that I don't need it for much of what I do.
Its the default behaviour for an enter button press in a non text area to post back a form. You would have to handle it in a javascript method to stop the postback.
You'd just need to check the window.event.keyCode property to see if its equal to 13. If it is, reset it to 0.
function KeyPress()
{
if (window.event.keyCode == 13)
{
window.event.keyCode = 0;
}
}
I suppose I could detect "enter" key presses from these text boxes with javascript
That's what I did to get around that behaviour and it works great in IE7 and FF3. It's just a little unnatural.
Here is a generic exemple:
function TextBox1_KeyDown(sender, e)
{
var key;
if(window.event)
key = window.event.keyCode; //IE
else
key = e.which; //firefox
if(key == 13 && $("#TextBox1").val() != "")
{
WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("TextBox1", "", true, "", "", false, true));
}
return (key != 13);
}
I used WebForm_DoPostBackWithOptions because I needed validators to trigger. Otherwise, you might want to use __DoPostBack.
Here are the "prototypes":
function __doPostBack(eventTarget, eventArgument)
function WebForm_PostBackOptions(eventTarget, eventArgument, validation, validationGroup, actionUrl, trackFocus, clientSubmit)
{
this.eventTarget = eventTarget;
this.eventArgument = eventArgument;
this.validation = validation;
this.validationGroup = validationGroup;
this.actionUrl = actionUrl;
this.trackFocus = trackFocus;
this.clientSubmit = clientSubmit;
}
function WebForm_DoPostBackWithOptions(options)
Hope it helps.
P.S.: I used JQuery here but $get would be the same.
Here's an elegant solution I have found, in case anybody else has this problem (in case all other solution don't work for you, as they didn't work for me):
<asp:UpdatePanel runat="server">
<ContentTemplate>
<asp:Panel runat="server" DefaultButton="doNothingButton">
<ul id="shopping-list-ul">
</ul>
<asp:Button CssClass="invisible" runat="server" ID="doNothingButton" OnClientClick="return false;" />
</asp:Panel>
</ContentTemplate>
The textbox iself was inside the ul (generated by javascript).
Pressing enter will trigger the "doNothingButton", which will return false on client side, causing no postback at all!

Resources