enter key in asp.net firing wrong button - asp.net

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{};");

Related

how to make enter key click on different buttons depending on which field is empty?

I have a web form in asp.net coding with vb and it has multiple textboxes and buttons. If one textbox is empty, I would like one button to be clicked if the enter key is pressed, whereas if a different textbox is empty, I would like the other button to be clicked, when the enter key is pressed. I know I can change the default button in the form section, but I don't know how I could go about changing the default button depending on which textbox is empty? I assume I have to do this in javascript, which I have little understanding of so any help would be much appreciated.
Can I do something like this to change the default button?
If txtMembranePressure.Text = "" Then
Dim sb As New System.Text.StringBuilder()
sb.Append("<form id='form1' runat='server'" + "defaultbutton='btnMembranePressure'")
Else
Dim sb As New System.Text.StringBuilder()
sb.Append("<form id='form1' runat='server'" + "defaultbutton='btnDiamondPressure'")
End If
Could I put the default button directly on the form like this?
Would it not be better to have one click routine - all buttons can freely point to that one click routine - but inside of that click routine, you can freely check the value(s) of the given text boxes, and then run the desired code. This seems a whole lot less complex then trying to change what actual button supposed to be clicked. So, have all buttons run the SAME routine, but that routine can simple check which text boxes have values in them.
Then based on what text boxes have (or have not) a value, you simple run or call the code you want based on this information.
Keep in mind, that in most cases, hitting enter key will trigger the button that FOLLOWS the control in the markup after that text box.
Edit: correction: the FIRST button on the page will trigger.
However, you can TURN OFF this behavour by setting in the button markup usesubmitBehaviour=False
<asp:TextBox ID="txtSearchOC" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button"
UseSubmitBehavior="False" />
In fact, if you drop a text box on a form, then say a gridview with 10 rows, and each row of the gridviewe has button with click event? Hitting enter key in above will in fact trigger the FIRST row button click of the gridview!!!
So, often by correct placement of buttons, say like a search text box, and a button after to click "search data", then in fact, if they hit enter key, the button that follows that text box will trigger anyway. (as noted, first button on markup fires - not any button, or not actually the one that follows the textbox).
So, in some cases, the correct order of a text box, and the button that follows can be put to good use here. But, often it can surprise you. You drop in a text box, and a form has 10 buttons that follow, ONE of them WILL trigger when you hit enter key - and this can often be harder to PREVENT this from occurring.
So, keep the above in mind. but, given that you want code to run based on values in text boxes (or lack of values), then I would have ONE routine that the button clicks ALL use, and the code behind can then check the text box values, and take the desired course of action and run your desired code based on this information.
There are 3 steps to do.
You need to know, when a Textbox is changed. For that you can use the TexboxChanged Event.
You need to know, if the Textbox is empty.
You need to know, how to change the default button.
Every Textbox need a TextboxChanged Event. And in every event you should check, if the Textbox is empty. If it is empty, you should set it to default.
In Pseudocode:
if Textbox.Text = "" then
set Textbox to default
For further information on the Textbox Change EVent, search in a searchengine (for example duckduckgo.com) for "textbox changed event":
https://meeraacademy.com/textbox-autopostback-and-textchanged-event-asp-net/
To change the default button, please consider following Answers at Stackoverflow:
How to set the default button for a TextBox in ASP.Net?
I have provided you with sufficient detail and example code below to re-engineer this yourself, even if I have not quite understood your requirement. I do agree with the comments above, this is probably not the best approach. You are better off checking server-side whether text boxes are populated or not, and then following a different path in your code.
JQuery lets you find elements by class name (CssClass="" in .NET, class="" on a normal HTML element)
$(".ClassName") makes JQuery find all elements with that class name on the page.
$("#Id") makes JQuery find all elements with that Id on the page.
data-whatYouWantToStore is a convenient way of storing data against an element, that you can then read with Javascript / JQuery. Just keep it all lower case to avoid upsetting it.
$(element).data("the name after the data- bit") will get you the value.
The only bits you need to change to make it run are on the text-boxes:
data-targetbuttonemptyclass="js-button-1" data-targetbuttonnotemptyclass="js-button-2"
Set the class of the button you want it to click when enter is pressed, if the textbox is empty in the data-targetbuttonemptyclass property, and the button to click if text is present in the data-targetbuttonnotemptyclass property. Text boxes must have the class js-click-if-not-empty set on them if you want them to be handled by the "empty / not empty" JavasScript.
<%# Page Language="vb" AutoEventWireup="false" CodeBehind="Buttons.aspx.vb" Inherits="Scrap.Buttons" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<!--Add reference to Jquery CDN -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<!--Your Javascript -->
<script type="text/javascript">
$(document).ready(function () {
// find all the buttons we want to set this behaviour on
$(".js-click-if-not-empty").each(function () {
// add a keypress event hander to each button
$(this).on("keypress", function () {
// get the key that was pressed
var keycode = (event.keyCode ? event.keyCode : event.which);
// is it the ENTER key?
if (keycode === 13) {
// prevent anything else that was going to happen because enter was pressed.
event.preventDefault();
// is the textbox empty?
if ($(this).val() === "") {
// yes - get the css class of the button to click when the textbox is empty
var button = $("." + $(this).data("targetbuttonemptyclass"))[0];
// just for debugging to show which button is about to be clicked
alert("going to click empty button: " + button.id);
// click the button
button.click();
} else {
// no - get the css class of the button to click when the textbox is not empty
var button = $("." + $(this).data("targetbuttonnotemptyclass"))[0];
// just for debugging to show which button is about to be clicked
alert("going to click not empty button: " + button.id);
// click the button
button.click();
}
};
});
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="tb_TextBox1" runat="server" CssClass="js-click-if-not-empty" data-targetbuttonemptyclass="js-button-1" data-targetbuttonnotemptyclass="js-button-2"></asp:TextBox>
<asp:TextBox ID="tb_TextBox2" runat="server" CssClass="js-click-if-not-empty" data-targetbuttonemptyclass="js-button-1" data-targetbuttonnotemptyclass="js-button-2"></asp:TextBox>
<asp:TextBox ID="tb_TextBox3" runat="server" CssClass="js-click-if-not-empty" data-targetbuttonemptyclass="js-button-1" data-targetbuttonnotemptyclass="js-button-2"></asp:TextBox>
<asp:Button ID="btn_ClickIfEmpty" runat="server" CssClass="js-button-1" Text="Click If Empty" />
<asp:Button ID="btn_ClickIfNotEmpty" runat="server" CssClass="js-button-2" Text="Click If Not Empty" />
</div>
</form>
</body>
</html>

How to give alert using Modal popup extender by clicking delete "image button" on gridview

Hi im having a modal popup extender for user confirmation to delete a file in gridview. I have given delete image button on the gridview.on delete image button click in every row of gridview, the control is passed to rowcommand function based on the command name of the image button. Before the control passes to rowcommand, it has to display an alert to delete "Do you want to delete?" if yes it has pass control to delete,if no it should not delete.
Thanks in advance.
this is my gridview_rowcommand function code
if (e.CommandName == "Delete") {
try {
int selectedrow = Convert.ToInt32(e.CommandArgument.ToString());// fetching the row
You are trying to get the server side to display the confirmation dialog. A better approach is to display this before the button posts back.
Here is an example that uses the standard Javascript confirm() dialog.
<asp:Button ID="btnDelete" runat="server" Text="Delete" CommandArgument='<Eval("ID")>' OnClientClick="return confirm('OK to Delete?');" />

How can i turn off ASP.NET required field validator "lost focus" behaviour

I have some code where I need two separate required field validators for one control, both in separate validation groups which are then validated by two separate buttons.
This approach works well when the buttons are clicked but both validators show if I enter a value in the textbox and then remove it.
Is there a way to turn this"lost focus" validation off? I only need it to validate when the buttons are clicked.
EDIT
Unfortunately, if I set EnableClientScript=false then I dont have any client notifications. What I want is for the dynamic error message to show (effectivly in the OnClientClick event of the button) but not the "lost focus" of the textbox.
Is there some way I can disable or "unhook" the lostfocus client event?
EDIT
A combination dDejan's answer and womp's answeer here sorted the problem perfectly.
My final code looks like this (for anyone else with a similar situation)...
Javascript...
<script type="text/javascript">
$(document).ready(function() {
$('body').fadeIn(500);
//Turn off all validation = its switched on dynamically
$.each(Page_Validators, function(index, validator) {
ValidatorEnable(validator, false);
});
});
function ToggleValidators(GroupName) {
$.each(Page_Validators, function(index, validator) {
if (validator.validationGroup == GroupName) {
ValidatorEnable(validator, true);
} else {
ValidatorEnable(validator, false);
}
});
}
</script>
ASPX Control Example...
<telerik:RadTextBox Width="196px" ID="txtFirstName" runat="server" MaxLength="50" Skin="Black"></telerik:RadTextBox>
<asp:RequiredFieldValidator ID="valFirstName" CssClass="Validator" runat="server" EnableClientScript="true" Display="Dynamic" ErrorMessage="You must enter your first name." ControlToValidate="txtFirstName" ValidationGroup="NeededForEmail"></asp:RequiredFieldValidator>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" CssClass="Validator" runat="server" EnableClientScript="true" Display="Dynamic" ErrorMessage="You must enter your first name." ControlToValidate="txtFirstName" ValidationGroup="NeededForSubmit"></asp:RequiredFieldValidator>
ASPX Button Code...
<asp:Button ID="btnGetConfCode" runat="server" Text="Get Confirmation Code" OnClientClick="ToggleValidators('NeededForEmail')" OnClick="btnGetConfCode_Click" Width="100%" ValidationGroup="NeededForEmail"/>
<asp:Button ID="btnRegisterUser" runat="server" Text="Register" OnClientClick="ToggleValidators('NeededForSubmit')" OnClick="btnRegisterUser_Click" Width="100px" ValidationGroup="NeededForSubmit" />
So, now there is no validation until a user clicks either the "Get Email Confirmation Code" button or the "Register" button.
If they click the "Get Email Confirmation Code" button all of the controls validate apart from the textbox where the user is to input the email validation code and we only see one validator message.
If they click the "Register" Button then all of the controls validate and we only see one validation message.
If either button is pressed, the user goes back, adds and then removes some text then we only see one validator. Before this change you used to see both messages saying the same thing.
Thank you for help guys
You can set if the validators are "active" or not with client side code using the ValidatorEnable function. Basically it goes like this
var validator = document.getElementById('<%=Validator1.ClientID%>');
ValidatorEnable(validator , state); //where state is boolean
You can also trigger the validator to validate on some event (like for example the click of the buttons) using the ValidatorValidate(validator) function.
I am not sure which would work better for you (enabling/disabling the validators or custom triggering of the validation) but I suggest this article that will guide you in the right direction
ASP.NET Validation in Depth
There's no way to unhook them if EnableClientScript=true.
What you could do is set it to false. Then create a javascript validation method that is called on your submit-button onClientClick event.
In your method, you would have to call ValidatorValidate(control) for each control you want to validate client side
There's an example here:
http://msdn.microsoft.com/en-us/library/Aa479045#aspplusvalid_clientside
You could turn off the javascript validation by setting EnableClientScript="false" that would get rid of the lost focus validation.
You can use Custom Validator controls instead and either validate the input using Javascript on the client or within the event handler on the server. Ensure you set ValidateEmptyText="true" on the validation controls otherwise the events will not fire on an empty field.
Try to Enable on Both button click using javascript and disable it on textbox blur event.
Try resetting the onchange event for the input-control.
$(document).ready(function () {
$("#controlid").each(function () { this.onchange = null; })
});
var validator = document.getElementById('<%=Validator1.ClientID%>');
ValidatorEnable(validator , state);
It is working in javascript but when we use the page.Isvalid function on Server side it creates the problem to check page is valid or not.
simply type this code in page_load event
textboxname.Attributes.Add("onblur","ValidatorOnChange(event);");

asp.net Button event inside jQuery FaceBox [duplicate]

This question already has answers here:
Facebox adding commas to input
(3 answers)
Closed 3 years ago.
I'm using jQuery FaceBox to show a textbox, a dropdownlist and a button. The user can write a text in the textbox, select a value in the ddl abd hit the button. This fires some code in the codebehind. The FaceBox shows fine, and the content in it is also ok. Also, the button event is fired. This is the code for the button event handler:
protected void Button1_Click(object sender, EventArgs e)
{
_favorit = new Favoritter();
ListItem fav = ddl_favoritter.SelectedItem;
_favorit.FavoritterFolderID = int.Parse(fav.Value);
//_favorit.FavoritterFolderID = Convert.ToInt32(ddl_favoritter.SelectedItem);
_favorit.FavoritterNavn = txt_favoritNavn.Text;
_favorit.FavoritterUserID = UserID;
_favorit.FavoritterUrl = HttpContext.Current.Request.Url.ToString();
FavoritterManager.InsertFavoritter(_favorit);
}
A business object is created, and its properties set with the values read from the controls. The object is then inserted into a database, which works just fine. The problem is that the textbox and dropdown values are not set properly. The textbox value is empty, and the ddl selected value is allways 1, even though I write in the textbox, and select another ddlitem before I hit the button. The ddl is loaded like this:
if (!Page.IsPostBack)
{
_favoritter = FavoritterFolderManager.GetFavoritterFolderByUser(UserID);
ddl_favoritter.DataSource = _favoritter;
ddl_favoritter.DataBind();
}
I tried putting this code outside if (!Page.IsPostBack), and also filling it using an objectdatasource, still the same issue. It's like the controls are "reset" as I hit the button, and I don't think it has anything to do with the FaceBox, as all it does is to show the div that contains the controls... Then again, it might... Any ideas?
This is the code in the aspx page:
<div id="showme" style="display:none;">
Add to favourites.<br />
<br />
<p>
Title: <span><asp:TextBox ID="txt_favoritNavn" runat="server"></asp:TextBox></span></p>
<p>
select folder: <span><asp:DropDownList ID="ddl_favoritter" runat="server" DataTextField="FavoritterFolderNavn"
DataValueField="FavoritterFolderID" AppendDataBoundItems="true">
</asp:DropDownList>
</span>
</p>
<br />
<asp:Button ID="Button1" runat="server" Text="Gem" onclick="Button1_Click"/>
</div>
You need to have the code that fills the text box and selects the drop down item inside of the if(!IsPostBack) block, because the page load event fires again before the button event (See the ASP.NET Page Life Cycle for more info on this). Have you tried enabling view state on the control? That may be part of the issue.
Change
$('body').append($.facebox.settings.faceboxHtml)
to
$('form').append($.facebox.settings.faceboxHtml)
The problem is a lot of these controls, not just FaceBox append themselves to the body by default. jQuery UI dialog does this as well.
See this question for a fix: JQuery Facebox Plugin : Get it inside the form tag
When things happen outside the <form> tag, they're disconnected from how ASP.Net works. When you clicked submit, the values from those inputs weren't inside the form, so didn't submit to the server...which is why you aren't seeing the values.
This is the quick answer from that question, credit to Kevin Sheffield:
poking around the facebox.js I came across this line in the function init(settings)...
$('body').append($.facebox.settings.faceboxHtml)
I changed that to ...
$('#aspnetForm').append($.facebox.settings.faceboxHtml)

Canceling the default submit button in 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;
}

Resources