Set enter key behavior on aspx form - javascript

Have the need to alter the behavior of pressing enter on my aspx page based on the last control that was interacted with. I have two textboxes and a dropdown. Each one of those controls has a corresponding button that takes the input and applies it to other fields on the page. Much like adding options to a master part.
Example: If button2 is pressed, the option in textbox2 would be applied, but not the option in textbox1, or the dropdown. The page is refreshed, and the user can continue to select options.
How would I alter the page to allow the user to type in text in a textbox and then hit enter to activate the code for the corresponding button. I've tried various js to set the page default, but have been unsuccesseful in changing this on the fly.

You can use ASP.Net Panel control's DefaultButton to accept enter key.
http://geekswithblogs.net/ranganh/archive/2006/04/12/74951.aspx
<asp:Panel ID="pnl1" runat="server" defaultbutton="Button1">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button1" OnClick="Button1_Click" />
</asp:Panel>
<asp:Panel ID="pnl2" runat="server" defaultbutton="Button2">
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:Button ID="Button2" runat="server" Text="Button2" OnClick="Button2_Click" />
</asp:Panel>

Set event listeners for a user modifying the inputs and set a reference to the proper button. Then have a listener for the enter button to trigger submitting the referenced button. You didn't mention jQuery or any JS framework so I'll try writing it generally for plain javascript, I'd recommend using a framework though for cross browser support.
var myButtonId = null;
var storeInputButtonId = function(buttonId) {
return function(event) {
myButtonId = buttonId;
};
};
//Do following for inputs, or your preferred event binding pattern
var fld = document.getElementById('myInputId');
//Statically refer to button id or replace with suitable algorithm
var inputButtonId = "";
if (fld.addEventListener) {
//Could bind to other events with logic based on input element type
fld.addEventListener('keyup',storeInputButtonId(inputButtonId), false);
}
//Method to trigger the button click event
function submitData(event){
//Watch for the enter button
if ( event.which == 13 ){
document.getElementById(myButtonId).click();
}
}
//Bind the listener to the enter button
var bodyElement = document.getElementsByTagName('body')[0];
if (bodyElement.addEventListener) {
bodyElement.addEventListener('keydown',submitData, false);
}

Related

How to focus a error after disable button 1st click using asp.net?

I have written code in asp.net for disable button after 1st click. Code is below:
<asp:Button ID="btnNext" runat="server" CssClass="btn btnBlue btnStep" Text="Submit"
OnClick="btnSubmit_Click" CausesValidation="true" ValidationGroup="ServiceFee" OnClientClick="this.disabled = true; this.value = 'In progress...';__doPostBack('btnNext','')" UseSubmitBehavior="false" />
It is working fine no problem but now I need to add little extra functionality i.e. I need to focus on error. When user clicks on submit button without entering card details or personal details it will show error at empty text box and suddenly page will reload, because i have written dopostback in javascript. So how to focus on error and after postback need to show error?
In the btnNext event you can have something like
// Supose txtCardDetails is the TextBox with the card details
if (string.IsNullOrWhiteSpace(txtCardDetails.Text))
{
ClientScript.RegisterStartupScript(this.GetType(), "script", "document.getElementById('" + txtCardDetails.ClientID + "').focus();");
return; // Maybe you want to do something before leave the event method
}
this will send a script to focus the field, BUT, I recommend to do the validation in the client side (JS) and in the Server side (C#), so, validating this in the client side should be like this
<asp:Button ID="btnNext" runat="server" ...
OnClientClick="return SubmitIfValid(this);" ... />
function SubmitIfValid(el) {
if(document.getElementById('<%= txtCardDetails.ClientID %>').value === ''){
alert('invalid card details');
document.getElementById('<%= txtCardDetails.ClientID %>').focus();
return false;
}
// more validations
// if all is OK then...
el.disabled = true;
el.value = 'In progress...';
__doPostBack('btnNext','')
return true;
}
You can use validation controls like validationSummary. Managing errors like those by yourself can be very difficult.

how to disable button after first click in javascript

I am new to C#. I have a save button inside InsertItemTemplate. I have used the following code to disable the button after first click in java script but its not even working for the first click please help me.
<asp:ImageButton ID="imgbtnSave" runat="server" CommandName="Add" CausesValidation="true" OnClientClick="this.disabled='true';return true;" />
You are modifying the "disabled" property of the DOM object on the browser, but the button will do a post back to the server when it's clicked, so any change to the DOM will be lost.
On the function where you handle the command "Add" in your server code you must retrieve the button from the InsertItemTemplate and set its "Enabled" property to false, that will disable the control from the server side.
If you want to avoid multiple clicks while the page has not been reloaded then you need a client function to avoid this, something like this:
<asp:ImageButton ID="imgbtnSave" runat="server" CommandName="Add" CausesValidation="true" OnClientClick="return checkEnabled(this);" />
<!-- somewhere in your page -->
<script>
function checkEnabled(item)
{
if(item.disabled != 'true')
{
item.disabled = 'true';
return true;
}
return false;
}
</script>

Client side keypress handling event, set focus function, and __doPostBack ASP.NET

I'm trying to do the following :
First, a textBox get the focus on page load (no problem here)
Then, when ENTER button is pressed inside that textBox, it switch focus to the second textBox.
Finally, when ENTER is pressed in that second textBox, it does a postback and reahes code behind event just like when you press a classic <asp:button />
Based on :
Fire event on enter key press for a textbox
and
JavaScript set focus to HTML form element
I managed to come up with :
HTML :
<asp:TextBox ID="txtNNoSerie" runat="server" Width="150px" ClientIDMode="Static" onkeypress="EnterEventFirst(event)" AutoPostBack="false"></asp:TextBox>
<asp:TextBox ID="txtNNoIdentification" runat="server" Width="150px" ClientIDMode="Static" onkeypress="EnterEventSecond(event)" AutoPostBack="false"></asp:TextBox>
<asp:Button id="btnAjouter" CssClass="ms-Button ms-Button--primary" onclick="btnAjouter_click" Text="+" ForeColor="White" runat="server" Width="30px" />
<input type="text" id="txtTest" /> <%-- Just for tests --%>
JS :
function EnterEventFirst(e) {
if (e.keyCode == 13) {
document.getElementById('txtTest').value = 'got it';
document.getElementById('<%=txtNNoIdentification.ClientID%>').focus();
}
}
function EnterEventSecond(e) {
if (e.keyCode == 13) {
document.getElementById('txtTest').value = 'Again';
__doPostBack('<%=btnAjouter.ClientID%>', "");
}
}
Code behind :
protected void btnAjouter_click(object sender, EventArgs e)
{
}
JavaScript functions are reached, because i can see "got it" and "Again" in the test TextBox, but just for half a second and then it desapear... The __DoPostBack funtion does not work.
Looks like when you press enter in a textBox, it automaticaly does a useless postback and page reload... And that is where i'm stuck
Use ClientID instead of UniqueID.
Well, textBox automaticaly postBack when enter is pressed, ok then.
I did it all on server side, I hate this but i kinda had no choice :
txtNNoSerie.Focus();
if (txtNNoSerie.Text != "")
txtNNoIdentification.Focus();
if (txtNNoSerie.Text != "" && txtNNoIdentification.Text != "")
btnAjouter_click(this, new EventArgs());
Server side code... If anyone can show me some working client side code i'll take it...

Detecting key combination in ASP.net

I have asp.net website. Here I have not used form tag for designing page but used div tags.
Now i want to read the key combination from user, example: if user presses keys "s+u+m" then I have to generate OnClick event of Sum Button on my ASPX page.
But it should be happen at page level not for control's key press
Also if there is an JS then please tell me where to write it as I am new in ASP.Net
Any Idea???
Thanks.
You can achieve this by control's AccessKey property.
But it will only allow 'Alt + Key' combination as you want PostBack on the key press.
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Button" AccessKey="P"
onclick="Button1_Click" />
</div>
</form>
'Alt + P' key combination on page will fire Button1_Click event.
If you want to make any key refer - js-hotkeys jquery plugin
Example: Binding 'Ctrl+P'
$(document).bind('keydown', 'ctrl+c', fnKeyCaptured);
function fnKeyCaptured()
{
__doPostBack(button.id,"OnClick");
}

Ignore .NET validators if element is hidden (display: none)

We often come into problems with .NET validators on elements that are hidden using javascript/css (ie. display:none)
For example (there may be syntax errors but don't worry about it)
<asp:CheckBox ID="chkNewsletter" runat="server" Checked="true" />
...
<div id='newsletterOnly'>
<asp:TextBox ID="txtEmail" runat="server" />
<asp:RequiredFieldValidator ID="vldEmail" ControlToValidate="txtEmail" ErrorMessage="Required" runat="server" />
</div>
with JavaScript:
$('#chkNewsletter').changed(function() {
$(this).is(':checked') ? $('#newsletterOnly').show() : $('#newsletterOnly').hide();
});
It should not validate txtEmail if it is hidden.
You can't submit the form if newsletterOnly is hidden, because the RequiredFieldValidator is still effective eventhough it is hidden :(
And you can't even see the validator error message because it is hidden
Is there any way around this?
I am trying to avoid PostBacks to improve user experience.
I wish I could modify .NET javascript to validate controls only when they are visible.
I wrote this as a general solution (can be used on all .NET websites).
You only need to add an OnClientClick to the submit button.
//===================================================================
// Disable .NET validators for hidden elements. Returns whether Page is now valid.
// Usage:
// <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClientClick="DisableHiddenValidators()" />
//===================================================================
function DisableHiddenValidators() {
for (var i = 0; i < Page_Validators.length; i++) {
var visible = $('#' + Page_Validators[i].controltovalidate).is(':visible');
ValidatorEnable(Page_Validators[i], visible)
}
return Page_ClientValidate();
}
To use it, simply include the above javascript and add the class OnClientClick="DisableHiddenValidators()" to the submit button:
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClientClick="DisableHiddenValidators()" />
EDIT:
jQuery $(submitButton).click function didn't work on iPhone/Android. I have changed the sample code above slightly.
If anyone see anything wrong or possible improvements please comment :)
It can also be a good idea to use Validation Groups in a situation like this. If you can group your validators then specify on the Button which validation group you need to validate against, only those validators in the group will be validated. Read more here:
http://msdn.microsoft.com/en-us/library/vstudio/ms227424(v=vs.100).aspx
Magic: Thankyou!
Modified slightly to include the ValidationGroup it resides in..
function DisableHiddenValidators(validationGroup) {
for (var i = 0; i < Page_Validators.length; i++) {
var isVisible = $('#' + Page_Validators[i].controltovalidate).is(':visible');
var isValGrp = (Page_Validators[i].validationGroup === validationGroup);
ValidatorEnable(Page_Validators[i], (isValGrp && isVisible)); //Turn on only if in Validation group and IsVisible = true
}
return Page_ClientValidate(validationGroup);
}
To add Custom DisableValidators method to the click event tree:
$('#myButtonControlId').on("click", function(e) { DisableHiddenValidators('Send'); });

Categories

Resources