Cancelling the keypress [Enter] action on a Telerik RadGrid - asp.net

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();
}
}

Related

ASP.net button is clicked in every page refresh

I have an asp.net button in my page, after I click the button, it is clicked again and again whenever I refresh the same page.
I tried;
if (!IsPostBack)
{
.....
}
for the click function of the button, but in this case button is not working.
<asp:Button ID="btnCommentSubmit" runat="server" Text="Submit" CssClass="leaveAComment" onclick="btnCommentSubmit_Click" />
above is the button.
protected void btnCommentSubmit_Click(object sender, EventArgs e)
{
string cityID = BusinessClass.Default.findCityIDByCountryAndCityName(Request.QueryString["city"].ToString(), "url").ToString();
BusinessClass.Default.makeComment(txtComment.Text, Session["userID"].ToString(), cityID);
txtComment.Text = null;
}
and this is the function.
If don't get you wrong your problem is when you hit F5 after clicking the button. Trying to resubmit the form is the normal behavior and is not related to asp.net but to browsers in general.
F5 causes to re-execute last request to the server, in your case, a POST request.
A way to avoid this issue is implementing the web pattern Post/Redirect/Get
Easy fix with a bit of JavaScript.
document.onkeydown = function() {
if(event.keyCode==116) {
event.keyCode=0;
event.returnValue = false;
}
}
This would stop the duplicate resend when you hit F5.

Using a button to open a link in a new tab/window in ASP.NET

I’m trying to use a button click to open a page in a new tab/window. I’ve looked at solutions similar to this, but the answers given there are either to use a link or have it open in the same window. I need to use a button because it needs to generate the link based on criteria data entered in the form (string manipulation). This button is not submitting the form though; it’s just validating some of the data on an external site. I need this in a different window or tab so they can go back and forth between my form and the validation site. This is basically my current Button_Click event:
var Address = AddressTextbox.Text.Trim();
Address = Address.Replace(' ', '+');
var Url = "http://www.example.com/query?text=" + Address + "&param1=foo&param2=bar";
Response.Redirect(Url);
This works except that Response.Redirect(Url) only opens in the same window, not a new one.
Just spit out javascript code from the Click event handler on the Button.
var Address = AddressTextbox.Text.Trim();
Address = Address.Replace(' ', '+');
var Url = "http://www.example.com/query?text=" + Address + "&param1=foo&param2=bar";
Page.ClientScript.RegisterStartupScript(this.GetType(), "dsadas", "window.open('"+Url+"');", true);
Use the OnClientClick attribute:
<script type="text/javascript">
redirectToPage = function(url){
void(window.open(url, "child_window"));
return false;
}
</script>
<asp:Button ID="Button1" runat="server"
Text="Click Me!"
OnClientClick="return redirectToPage('/somefolder/somepage.aspx');" />
Using the OnClientClick attribute, it's important to remember to return false at the end, otherwise the button click will trigger a postback.
EDIT
If you want to open a new window from the click event handler, you can do something like this:
protected void Button1_Click(object sender, EventArgs e)
{
Page.ClientScript.RegisterStartupScript(Page.GetType(), "open_window",
string.Format("void(window.open('{0}', 'child_window'));", "/somefolder/somepage.aspx"), true);
}
Admittedly, this is kind of ugly, but if there's certain information that you won't have until the button click logic is executed, this might be your best option. If there's any way you can build the URL before the button is clicked, you can just assign the OnClientClick in code-behind.

Difference between onkeypress and onkeydown in asp.net

I have a form with a default button set.So when i press enter,form is submitted regardless of the focus. My requirement is when focus is inside fileupload control and enter is pressed,instead of submitting the form show browse dialog. So I created a panel and attached a onKeyPress event to this panel
fileUploadDocument.Attributes.Add("onkeyPress", "return ByPassEnter(event);");
<asp:Panel ID="fileUploadDocument" runat="server">
<div>
<uc2:FileUploadControl ID="ucdocxUploadControl" runat="server" ErrorMessageNoFileSelected="Please select a file for upload."
ValidationGroup="BrandLogoFileUpload" />
</div>
</asp:Panel>
function ByPassEnter(e) {
var evt = (e) ? e : window.event;
var key = (evt.keyCode) ? evt.keyCode : evt.which;
if (key == 13) {
document.getElementById('<%=ucdocxUploadControl.BaseFileUploadControl.ClientID %>').click();
CancelDefault(evt);
}
}
function CancelDefault(e) {
e.cancel = true;
if (e.preventDefault) {
e.preventDefault();
}
e.returnValue = false;
}
When i press enter on fileupload control, browse dialog shows up and when i choose a file or hit cancel on browse dialog,postback happens. e.returnValue = false should prevent the postback but even then postback happens.
However if i change onkeypress to onkeydown,everything works and postback doesnot happen.Can somebody tell me the difference in these events and why postback is happening in onkeypress.
The keypress event fires after the key is pressed and released. At that point your form's submit action is activated.
keydown fires after the press but before the release. At that point you can cancel the keypress from registering.

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

Javascript : Enter Key Press

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>

Resources