TextBox causes Button Postback in ASP.NET - 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!

Related

Control in UpdatePanel not found using $find

I have a complicated page but I created a simple ASP.NET page with the issue. I have telerik RadAsyncUpload control and a button inside an UpdatePanel as shown:
<asp:UpdatePanel ID="_updatePanel" runat="server" UpdateMode="Conditional">
<ContentTemplate>
...
<telerik:RadAsyncUpload ID="fileUpload" runat="server" MaxFileInputsCount="1" OnClientFilesSelected="fileUpload_ClientFilesSelected" /><br />
<asp:Button ID="_saveNewFileButton" runat="server" OnClick="_saveNewFileButton_Click"
Text="Save"/>
</ContentTemplate>
</asp:UpdatePanel>
When a file is selected I want to disable the _saveNewFileButton and change the text to "Please Wait for Attachment Upload..." but I can't seem to get hold of the button reference in javascript:
var FilesUpdateInterval = null;
//Handles client side FilesSelected event for _newFileUploadButton.
function fileUpload_ClientFilesSelected(sender, args) {
//disable the click event for submit button during upload
var submitButton = $find('<%= _saveNewFileButton.ClientID %>');
submitButton.set_text('Please Wait for Attachment Upload...')
submitButton.set_readOnly(true);
if (FilesUpdateInterval == null) {
FilesUpdateInterval = setInterval(function () { FileCheckForUploadCompletion(); }, 500);
}
}
I am getting submitButton is null error. I tried putting this javascript code outside the updatepanel and inside ContentTemplate with same result. Obviously whatever I am doing is wrong. How do I get hold of the control that is in updatepanel in javascript?
EDIT: I find out that $find works with only telerik controls. So, I have to either use document.getElementById function or JQuery with something like Steve specified. Also, I have to use RegisterClientScriptBlock. I will test with Steve suggestion and then accept the answer.
short version - use $get() or document.getElementById(), as regular HTML elements are not IScriptControls, so $find() will not give you anything, and they don't have the rich client API you are trying to use.
For example
var submitButton = $get('<%= _saveNewFileButton.ClientID %>');
submitButton.setAttribute("value", "Please Wait for Attachment Upload...");
Option 2 - use RadButton.
Using jQuery and vb with ASP.Net, I've done something similar to this, which has worked well, even if it isn't that pretty. The [Whatever] I have was a FormView that didn't always have the control. Also, I didn't use it with a button, but I think that's the syntax for changing the button text. Either way, it might give you some ideas:
$('#<%=GetButtonClientID("_saveNewFileButton")%>').attr('value', 'Please Wait for Attachment Upload...');
And then I have a function like this:
Public Function GetButtonClientID(ByVal argFieldName As String) As String
Dim tmpID As String = "0"
Dim tmpButton As Button = [Whatever].FindControl(argFieldName)
If Not tmpButton Is Nothing Then Return tmpButton.ClientID.ToString Else Return "0"
End Function

Before deleting a row in repeater , i want to do validation asking that, are sure you want to delete..?How can i do this?

i want to do validation asking that, are sure you want to delete..?
<asp:LinkButton ID="lnkDelete" runat="server"
CommandName='<%# DataBinder.Eval(Container.DataItem, "ImageId") %>' OnCommand="Calling_Delete">Delete</asp:LinkButton>
The easiest way to do it is to use Confirm Button extender. Just drag this control next to the linkbutton and set the Confirmbutton externders TargetControlID to the Id of the Linkbutton. Everything else will be taken care of by the control.
More info- http://www.asp.net/ajaxLibrary/AjaxControlToolkitSampleSite/ConfirmButton/ConfirmButton.aspx
Use OnClientClick property to attach the java-script that will do the prompting. For example,
<asp:LinkButton ID="lnkDelete" runat="server"
CommandName='<%# DataBinder.Eval(Container.DataItem, "ImageId") %>'
OnClientClick="return confirm('Are sure you want to delete..?');"
OnCommand="Calling_Delete">Delete</asp:LinkButton>
This answer has one way to do it, using jQuery and a jQuery UI dialog
One advantage of using a javascript dialog such as that provided by jQuery UI is that the popup dialog is modal only for the web page on which it is displayed. You can still access other tabs within your browser while the popup is displayed.
Other solutions that use the javascript confirm function will force the user to dismiss the confirmation dialog before switching to another browser tab.
if u'd like to use custom confirmation ( like jquery dialog,bootboxjs etc.. ) then you have to generate button's "postback string" or get it somehow. asp.net gives such as postback name after rendering the page; __doPostBack('ctl00$ContentPlaceHolder1$btnDeleteSelected',''). after realizing this i wrote a js function which is generates button's postback str;
function PostBackBtnMake(id) { // id : ContentPlaceHolder1_btnDeleteSelected
var result;
var temp = id.split('_');
result = 'ctl00$' + temp[0] + '$' + temp[1];
return result;
}
then i be able to use in custom confirmation box (in this case i used bootboxjs);
function PostBackBtn(e) {
var _result = false;
bootbox.confirm("Are you sure?", function (result) {
if (result) {
__doPostBack(PostBackBtnMake(e.id), '')
}
});
return _result;
}
it's worked for me, i hope it helps you too.

Display in correct order using RequiredFieldValidators, ValidatorCallout and a ModalPopupExtender of validation is OK

I'm trying to get a sequence of things to happen in the correct order, but no luck. What I have is a number of fields with asp:ReuiredFieldValidators and asp:ValidatorCallout to display validation messages. This is triggered with a button Save with validation="true".
If all validates, it should display a modal dialog asking for two choises on how to save the data. No matter the answer, it should always continue at this stage to code behind save function.The AjaxToolkit_ModalPopupExtender is connected to the same save button.
What happens is that the validation callouts and modal dialog is shown at the same time.
Searched for tips and help but haven't found any, for me, helpful! Most grateful for any help!
Cheers
/Johan
You can show the ModalPopup from codebehind(in BtnSave.Click-handler) if the page is valid:
Page.Validate("YourValidationGroup");
If(Page.IsValid){
ModalPopup1.Show();
}
Therefor you need to set the TargetControlID of the ModalPopupExtender to a hidden button:
<asp:Button ID="Hid_ShowDialog" Style="display: none" runat="server" />
You must move to Code Behind only when the Page is validated in client side. You can do it using OnClientClick of button
<asp:Button ID="ShowDialog" onClientClick = "return ValidatePage();"
runat="server" />
<script type="text/javascript">
function ValidatePage() {
if (typeof (Page_ClientValidate) == 'function') {
Page_ClientValidate();
}
if (Page_IsValid) {
// do something
alert('Page is valid!');
return true;
}
else {
// do something else
alert('Page is not valid!');
return false;
}
}
</script>

How to disable submit behaviour of asp:ImageButton?

I have a image button in a page which can be triggered on mouse click, by default it gets triggered on enter press also which i want to disable.
I know about "UseSubmitBehaviour" attribute in asp:Button, is there a way to do the same in asp:ImageButton?
I will assume you have some sort of input controls and you don't want an enter keypress to auto submit when a user accident hits the enter key. If so you can attach a javascript onkeypress event to each control that you want to disable this behavior for.
function disableEnterKey(e)
{
var key;
if (window.event) key = window.event.keyCode; // Internet Explorer
else key = e.which;
return (key != 13);
}
// In your aspx file Page_Load do the following foreach control you want to disable
// the enter key for:
txtYourTextBox.Attributes.Add("OnKeyPress", "return disableEnterKey(event);");
If you need to disable the Enter key submitting form completely. case use the OnKeyDown handler on <body> tag on your page.
The javascript code:
if (window.event.keyCode == 13)
{
event.returnValue = false;
event.cancel = true;
}
With JQuery this would be much cleaner, easier and the recommended method. You could make an extension with:
jQuery.fn.DisableEnterKey =
function()
{
return this.each(function()
{
$(this).keydown(function(e)
{
var key = e.charCode || e.keyCode || 0;
// return false for the enter key
return (key != 13);
})
})
};
// You can then wire it up by just adding this code for each control:
<script type="text/javascript" language="javascript">
$('#txtYourTextBox').DisableEnterKey();
</script>
If you put your content in a asp:Panel you can use the DefaultButton Property to set a different button as the default so your image button wont be clicked.
<asp:Panel runat="server" ID="pnl_Test" DefaultButton="btn_Test2">
<asp:ImageButton runat="server" ID="btn_Test1" />
<asp:Button runat="server" ID="btn_Test2" />
</asp:Panel>
In this example the btn_Test2 will be clicked when you hit enter where normally btn_Test1 would be clicked
Use Kelsey's Answer (This answer is wiki'ed)
...but please note a few things when you implement it.
I'd recommend the plain old javascript method if you're not already using jQuery. if you do that method, just return (keynum != 13) don't do something silly like if(true) return true; else return false;
You don't have to assign onkeydown from the code behind. That can be done in the markup and it's a lot cleaner when you do.
Don't disable the enter key in your entire form. You can do it in your inputs only, but if you do it in the entire form you won't be able to add a carriage return in a textarea.
If you do use jQuery, I'd recommend adding a CSS class called "disableEnterKey" and assigning it to your form elements you want to disable, then calling Kelsey's jQuery method on $(".disableEnterKey") in the document ready.
Don't answer too similar to anyone on SO, even if you don't fully agree with the answer. And even if the answer was simple and thousands of people probably have done the samething. It's "copying". Which is similar to being a "cutter" or a "tattle tale"... which is bad.
(this answer has been community wiki'ed as this question thread has gotten silly)
Use an asp:image instead. Then place some javascript code in the onclick "javascript:document.getElementById('imageClicked').setAttribute('value', 'true'); document.myform.submit();"
Set a hidden field's value (using javascript) to tell the server side code that the image was clicked.
document.getElementById('imageClicked').setAttribute('value', 'true');
Then, at the end of handling the postback on the server reset the hiddenField's value:
document.getElementById('imageClicked').setAttribute('value', 'true');
The form will execute the first button it finds on the page when you hit enter. If you can move the ImageButton further down the page so it's no longer the first button in the markup, and use CSS to position it properly, this should fix your issue. I fixed the same exact thing last week and this worked for me. I went with this solution because it didn't require JavaScript to work properly.
you want something like
<form ...>
<!-- some code here -->
<button style='display:none' onclick='return false'>here comes the magic</button>
<button>normal button </button>
</form>
See the following link.This can be solved for all default button submit problem.
http://weblog.kevinattard.com/2011/08/aspnet-disable-submit-form-on-enter-key.html
Please Use This Code
<script type="text/javascript" language="javascript">
$(document).ready(function {
$("#<%=imageClicked.ClientID%>").prop('disabled',true)
});
</script>

Making ASP label visible in Javascript?

This is my label I want to display if the user have left out field before clicking the button. What am I doing wrong because nothing is happening when I click the button.
<asp:Label ID="lblError" runat="server"
Text="* Please complete all mandatory fields" style="display: none;" >
</asp:Label>
This is the function I call when I click on the button:
function valSubmit(){
varName = document.form1.txtName.value;
varSurname = document.form1.txtSurname.value;
if (varName == "" || varSurname == "")
{
document.getElementById('lblError').style.display = 'inherit';
}
else
{
.................other code go here...........................
return true;
}
}
Why not use the Validation controls? These will give you client and server side validation out of the box - not that I'm lazy or anything... ;-)
Edit for comment:
The RequiredFieldValidator can be set to display a single red asterisk by the side of each control, and a validation summary control could be used BUT that would take up space.
So, it's possible that ASP.Net is renaming your control, so your JS should read:
document.getElementById('<%= lblError.ClientID %>').style.display = 'inherit';
Give that a go...
Personally, I'd still use the Validator controls ;-)
You shouldn't be using lblError as an ID in JavaScript code. Instead you should use:
'<%= lblError.ClientID %>'
Of course this is only possible if you are generating the JavaScript code in the ASP.NET file.
on your desired event use this
document.getElementById('<%= lblError.ClientID %>').style.display = ""; or
document.getElementById('<%= lblError.ClientID %>').style.display = "block"
ok then try this, instead of client side, make it serverside. First set it invisible like , on formload event set invisible using lblEror.visible = false and remove style ="display:none" from html.
Then on the desired event/s make it visible and after processing again invisible.
If you want it strictly thorugh js.try this workaround. remove style from asp label. on body onload make it disable from some js function. now on the btn click event make it visible using the method something like this
function Validate()
{
var objLbl = $get('<%=lblError.ClientID%>');
if (validations fails)
{
objLbl.style.display = ""; //displays label
return false;
}
else
{
objLbl.style.display="none" //hides label
return true;
}
}
<asp:button id="btnValidate" runat="server" onclientclick="return validate();"/>
Hope this will work
Take a look at jquery, you can select by classes instead of id's which will never be altered when rendered onto the page (unlike id's)

Resources