ASP.NET and JQuery - Default Button Click - asp.net

I have an ASP.NET page that is basically a search form. My code for this form looks like this:
<form id="mainForm" runat="server">
Search For: <asp:TextBox ID="searchTB" runat="server" />
<input id="myButton" runat="server" type="button" value="Go"
onclick="disableButton(this);" onserverclick="myButton_Click" />
<script type="text/javascript">
function disableButton(b) {
b.disabled = true;
b.value = "Searching...";
}
</script>
</form>
This code works fine as long as a user manually clicks the button. However, if a user hits the "Enter" key, the search is not performed. My question is, how do I set an HTML button to the default button in an ASP.NET page when client-side scripting is involved?
Thank you!

Have you tried the onkeypress event? Bind it to the same function and it should work.

For enter to work by default, your button needs to be the first one on the page and it should be type="submit" rather than type="button".
You could also try changing your input to a standard asp.net button. If you change your javascript function to return true, the post click of the button should still work. However to bind 2 events to the button you may need to add the client side click in your page load method.
myButton.Attributes.Add("onclick", "return disableButton(this)");

ASP.NET 2.0 - Enter Key - Default Submit Button

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 hide ajaxtoolkit calendarextender when lost focus?

Hi,
I want to hide first calendar when a second is open or when the calendar field lost focus. The issue is that if the user doesn't select any date from calendar and go to other control in page the calendar doesn't hide, only when user select any date from calendar the popup hides. This capture show the problem.
I see that in ajaxtoolkit calendarextender sample page the calendar control works fine, when out from one to another calendar prior popup hides but I don't find the sample code of this page. I think this page manage in javascript the event when the focus is lost, but I had found any sample code or project ...
Thank you in advance!
As Yuri mentions, using an ImageButton fixes this... or...
You need to handle the onmouseout event. You can do it this way:
http://forums.asp.net/p/1182269/4708411.aspx/1?Re+Calendarextender+and+Lose+Focus+Or+Mouse+Out
Or you could add some javascript (via jQuery) and inject an onmouseout event:
Adding extra functions to an image's onmouseout attribute
This is also shown in the forums.asp.net link, but basically, on the onmouseout event you can just set the visibility of the calendar extender to hidden or none.
As an option in addition to solutions provided by dash, you may use following decision if you don't want to use ImageButton instead of Image for PopupButton: set OnClientShowing properties on extenders to "hideAnotherOpenedPoups" and add onto a page script below.
// Array of BehaviorIds of each extender for those you use Image as PopupButton
var behaviorIds = ["CalendarExtender1", "CalendarExtender2"];
function hideAnotherOpenedPoups(sender) {
for (var index = 0; index < behaviorIds.length; index++) {
if (behaviorIds[index] !== sender.get_id()) {
var extender = $find(behaviorIds[index]);
if (extender.get_isOpen()) {
extender.hide.call(extender);
}
}
}
}
Try the following line of code to show the calendar on both Textbox and Image click.
<asp:TextBox runat="server" onclick="showCalendar();" onfocusout="showCalendar();" ID="txtDate" />
<asp:ImageButton runat="Server" ID="imgPopup" AlternateText="Click to show calendar" />
<cc1:CalendarExtender ID="CalendarExtender1" runat="server" TargetControlID="txtDate" CssClass="MyCalendar" Format="MMMM d, yyyy" PopupButtonID="imgPopup" />
and add a javascript function like this
<script type="text/javascript">
function showCalendar() {
$( "#<%=imgPopup.ClientID %>" ).trigger( "click" ); //I've used .ClientID here just in case your page is inherited from a Master page
}
</script>
That should display the calendar when you click on the Textbox, and the calendar will be hidden once you click anywhere else on the form

How to hide Label in asp.net

i m working on simple asp.net and in that i am using validators.
my situation is like that i have used reaquired field validator its working fine.
and after that if i ented data and fired insert query then data is inserted and sucessful message is displyed on the lable. but agin if i clik on submit button with empty fields then validator works but the lable of successful message does not disapper. how to hide that lable.
You need to use javascript to hide the success message, here is a sample
<script type="text/javascript">
function hide() {
document.getElementById('<%=lblSuccess.ClientID %>').style.display = 'none';
return false;
}
</script>
<asp:Label ID="lblSuccess" runat="server" Text="Success"></asp:Label>
..your form code
<asp:Button ID="btnOk" runat="server" Text="OK" OnClientClick="hide()" ValidationGroup="ValidateForm" />
Why javascript, the form doesn't get posted because validators don't let the form to be posted if the conditions aren't met, so you are left to hide the message dynamically with javascript
<script type="text/javascript">
function Hide() {
document.getElementById("Lable1").style.display = 'none';
return false;
}
</script>
<asp:Button ID="Button1" OnClientClick="Hide()" runat="server" onclick="Button1_Click" Text="Button"/>
and use
if (Page.IsValid){}
on clik event.
Show us some code of what you're up to and we can tell you more precisely where you are going wrong. In a nutshell though the visibility of that message is going to be persisted through a postback so you have to explicitly tell it to not be visible if validation has failed.
Set the label to visable=false and on save set the text value if required and change visible =true ?
On form load, do something like this:
TheValidMessageLabel.Visible = Page.IsValid;
You are probably just setting the visible state to true when it's valid and never setting it to false again.
Set your success label visibility in page load to false.
And only if operation is successfully set that label visibility to true.
cheers

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

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

Resources