Javascript : Enter Key Press - asp.net

Good Morning...
I am using java script in each page to trigger the Enter key press Event inside the textbox.
It is working fine. Now i want to place the code in the .js file for global access.
function EnterKeyPress(id,e) {
// look for window.event in case event isn't passed in
if (window.event) { e = window.event; }
if (e.keyCode == 13 || e.keyCode == 121) {
window.document.getElementById('<%= ibtnSubmit.ClientID %>').click();
}
}
I dont want to hard code the control id. Can anybody help me please..

You can use your id parameter instead of the ControlID, and when you use this function in your pages, you can pass the ControlID as a parameter:
function EnterKeyPress(id,e) {
if (window.event) { e = window.event; }
if (e.keyCode == 13 || e.keyCode == 121) {
document.getElementById(id).click();
}
}
You are using ASP .NET, so in your code-behind you can assign the keypress event:
TextBox1.Attributes.Add("onkeypress",
string.Format("EnterPressKey('{0}', event);", ibtnSubmit.ClientID));
But wait, that functionality is already done on ASP .NET, you can use ASP:Panel controls to wrap your common controls, and you can assign a DefaultButton for the panel to indicate which button gets clicked when the Panel control has focus and the user presses the Enter key.

If you're using jQuery you can do it like this:
$("input[id*=ibtnSubmit]").click()

If you want the form to submit when the user presses the Enter key, then you don't need javascript. It will do so automatically. Just put the textbox inside a form element with an action:
<form action="process.php">
<input type="text">when the enter key is pressed, the form is submitted and sent to process.php</input>
</form>

Related

Hitting Enter on TextBox Submits

I am working on a user control (ascx) with an asp TextBox control.
Whenever I press the enter key on the TextBox, the user control automatically submits it.
I do not want that to happen. I want to disable automatic submit on press of the enter key on any other control aside from the Submit Button.
Please note that I do not use any HTML controls aside from Table.
Thanks!
You can put javascript code and disable Enter Key event ...
<div onkeypress="return noenter(event)">
javascript code :
<script language="javascript" type="text/javascript">
function noenter(e) {
e = e || window.event;
var key = e.keyCode || e.charCode;
return key !== 13;
}
</script>

Cancelling the keypress [Enter] action on a Telerik RadGrid

I have a Telerik Radgrid containing all the valid usernames and passwords that can be used to unlock functionnalities on my web page.
The password is encrypted, so you have to click the row to decrypt and show the actual password. All usernames and passwords can be changed by an admin
When the admin presses [ENTER] to submit the new username/password combination (instead of pressing the submit button), the new combination is actually submitted (which is fine).
However, my problem is that, by default, the RadGrid selects the next row, which decrypts the password and lets you edit the username/password.
Ideally, pressing [ENTER] would only submit the username/password combination, not selecting any other row. If that's not possible, pressing [ENTER] should not do anything.
If have tried the following javascript code:
<script type="text/javascript">
function KeyPressed(sender, eventArgs) {
if (eventArgs.get_keyCode() == 13)
{
alert("Cancelling event");
eventArgs.set_cancel(true);
}
}
</script>
The alert box is raised, but the [ENTER] event is not interrupted.
Edit: Note that the alert is for testing only!
I have also added this code to my RadGrid control to add KeyPress capture
<ClientSettings EnableRowHoverStyle="true" EnablePostBackOnRowClick="true" ClientEvents-OnKeyPress="KeyPressed" AllowKeyboardNavigation="true">
<Selecting AllowRowSelect="True" />
</ClientSettings>
My question is: How can I interrupt the [ENTER] keypress event? Or modify its behavior?
Any hints will be appreciated
I am using VB.net on Visual Studio 2008.
I am using ASP.net version 2.0
Here is my javascript code to cancel an event on enterkey.
function CheckKey() {
if (event.keyCode == 13) {
CancelEvent();
}
}
function CancelEvent() {
var e = window.event;
e.cancelBubble = true;
e.returnValue = false;
if (e.stopPropagation) {
e.stopPropagation();
e.preventDefault();
}
}

Default key for a button inside the gridview ASP.NET C#

I am trying to assign the Enter key to a button inside of a gridview. Does anyone know how this can be accomplished? Thank you.
You can give the button an id on one of the rendering events of the GridView, and then with jQuery bind the keypress() to a main div that wraps your site, and have it simulate the click() event on the button in your gridview when the 'enter' key (keyCode 13) was detected.
Like this :
$(document).ready(function() {
$('#mainDivWrapperId').keypress(function(event) {
if (event.keyCode == '13') {
$('#buttonId').click();
}
});
});
Edited Addition :
If you have a button in a gridview, then you just need to catch the 'enter' key press event like I've shown above, and then you can have it trigger the 'click' event of your button.
Like this :
$(document).ready(function() {
$('#mainDivWrapperId').keypress(function(event) {
if (event.keyCode == '13') {
$('#buttonId').trigger('click');
}
});
});
actually to make it simple,
1st declare the button on click event handler.
2nd declare a on keydown/keypress event handler for grid view.
inside the gridview's keypress/keydown event handler, check for keycode 13 from the event argument.
if the event.keycode==13, do button.click().
what ever logic inside the button's click event handler will be processed.

Pressing enter on any textbox invokes my Save button click event?

I have a standard asp.net webform with multiple textboxes (Autopostback=False) on it and a Save button.
Pressing ENTER while in any textbox is causing the server side click event of the Save button to be invoked. If I break and look at the call stack, the click event is the only event listed. I do not have a default button set for the form.
If I put another button above the save button, then it gets its click event invoked on any press of enter on a textbox.
Any ideas why this is happening, and how to get it to stop?
This is the default behaviour for most fields except for text areas.
To get around this you can call a javascript function before the form is submitted to check the keypress.
<script type="text/javascript">
function allowSubmission() {
return !(window.event && window.event.keyCode == 13); }
</script>
Then the only way to submit the form is to actually hit submit. However as many people have mentioned, the enter key submitting a form is expected behaviour, so you can always alter the function to do basic validation on the fields, allowing the enter key to submit the form if all the required fields have been filled in.
<script type="text/javascript">
function allowSubmission() {
return !(window.event && window.event.keyCode == 13) || validateInput(); }
</script>
Edit: You'd call this function on the OnClientClick method of your submit button. Something like:
<asp:Button id="SubmitBtn" runat="server" OnClientClick="return allowSubmission()"/>
This is true for any webform: if you press enter while an input field has focus, the form will be submitted (except textareas). To stop that, you'll need some JavaScript to capture that event and prevent the form being submitted. Be aware though, pressing enter to submit is expected behavior for many users!
Make sure your text boxes are set to Multiline as TextMode, if not enter key is executing a command button causing the post back.
<asp:TextBox ID="TextBox1" runat="server" TextMode="MultiLine"></asp:TextBox>
If you do not want your text boxes multi-line, you can intercept the key press command in JavaScript to do nothing when entered is pressed.
This is an example how
function hookUpToEnterKey()
{
// Hook up to read enter key
document.onkeydown = processEntryKey;
}
function processEntryKey(e)
{
if( !e )
{
if( window.event )
{
//Internet Explorer
e = window.event;
}
else
{
// Cannot get the even return.
return;
}
}
if( typeof( e.keyCode ) == 'number' )
{
//DOM
e = e.keyCode;
}
else
if( typeof( e.which ) == 'number' )
{
//NS 4 compatible
e = e.which;
}
else
if( typeof( e.charCode ) == 'number' )
{
//also NS 6+, Mozilla 0.9+
e = e.charCode;
}
else
{
//total failure, we have no way of obtaining the key code
return;
}
if(e == 13)
{
// Do nothing
return false;
}
}
I had the exact same problem: I had a databound gridview, a textbox and a button. The textbox was used to filter the grid contents, as a search box. The button was used for a totally different action. Before putting the button, hitting the enter key on the textbox caused the grid to be filtered, which was expected behavior. But as soon I put the button, hitting enter while focus on the textbox caused the onclick event of the button to be called. I fixed it just by setting to true the autopostback property of the textbox. I don't understand why, but somehow it overrides the form submission behavior of the textbox. Hope it helps
Your browser is trying to be a nice guy and click the button for you, even if you didn't set it to be the "default" (it will "click" the first button in the form on enter).
Like David said, if you want the enter key to cause a line break in the textbox, it needs to be multi-line

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