OnClientClick preventing OnClick event? - c#

I have a button, I need to fire an onclick event, and an onclientclick event. The onclientclick would be something like this:
(function($){
$.fn.validate = function() {
var option = $('#<%=LblWarnings.ClientID%>').html();
if (option == "option1_OK" ||
option == "option1_OK")
alert(wrong);
else {
$('#<%=LblWarnings.ClientID%>').html("Incomplete");
alert(wrong);}
};
})(jQuery);
Validating function, checks the text of a label, if condition's true it should go on and execute the OnClick event. And if it's false, it should NOT FIRE the code behind (method called WriteInfo in my .cs file, but just update a label so the user knows something was wrong while he was submitting data.
Is it possible for the onclientclick to stop the onclick event? If so, could you help me providing me the asp:button sentence so I can trigger both events.
Thanks.
After trying Adil Answer, I get an error "object expected"
Maybe there's something wrong the way I'm calling the function?
<asp:Button ID="ButtonRadioValue" CssClass="customButton" runat="server" onclick="WriteInfo" OnClientClick="validate();" Text="Accept" />

You can use stopPropagation() method to stop postback of return false.
Use stopPropagation();
(function($){
$.fn.validate = function(event) {
var option = $('#<%=LblWarnings.ClientID%>').html();
if (option == "option1_OK" ||
option == "option1_OK")
alert(wrong);
event.stopPropagation();
else {
$('#<%=LblWarnings.ClientID%>').html("Incomplete");
alert(wrong);}
};
})(jQuery);
Using return false;
(function($){
$.fn.validate = function() {
var option = $('#<%=LblWarnings.ClientID%>').html();
if (option == "option1_OK" ||
option == "option1_OK")
alert(wrong);
return false;
else {
$('#<%=LblWarnings.ClientID%>').html("Incomplete");
alert(wrong);}
};
})(jQuery);

Related

pop up does not go for post back in asp.net

I have button called sales and it have a JavaScript popup when I click on cancel it postback and the values in the form are inserted but when i click on ok it does not post back and the values in the form does not go in the database ( the JavaScript button is actually print call and when button is clicked it asks for print when print dialog box is open it does not post back and data is not inserted in the database)
here is the javascript code
function confirmAction(printable) {
var r = confirm("You want to Print Invoice?");
if (r == true) {
var printContents = document.getElementById(printable).innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
__doPostBack();
}
else {
__doPostBack();
}
}
here is the code for button click
<asp:Button ID="btnaddsale" runat="server" Text="Sale" OnClick="btnaddsale_Click" OnClientClick="javascript:confirmAction('printable')"/>
Ok, couple of notes for you:
You want a postback in either case.
Your <asp:Button> will automatically do a postback either way, so you don't need to call __doPoskBack(); in this scenario.
Major issue here is that, if you want a postback, it will happen immediately when the function exits, effectively canceling out the print dialog too soon. To avoid this, we will use a JavaScript trick that will check if the document has focus, and only when it does (when user exits print dialog in the browser) will we return and allow the postback to occur.
To fix the issue,
First: Make the function return true; when user cancels, and wait for focus and then return true if the user wants to print:
function confirmAction(printable) {
var r = confirm("You want to Print Invoice?");
if (r == true) {
var printContents = document.getElementById(printable).innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
// Check focus after user exits print dialog and then return true for the postback
var document_focus = false;
$(document).focus(function () { document_focus = true; });
setInterval(function () { if (document_focus === true) { return true; } }, 500);
}
else {
return true;
}
}
Then, change the JavaScript code to use the return statement in the OnClientClick event:
<asp:Button ID="btnaddsale" runat="server" Text="Sale"
OnClick="btnaddsale_Click"
OnClientClick="javascript:return confirmAction('printable')"/>
Update based on comments and your changed requirement:
Here's a snippet to make the script pop up after the postback. So you will insert values to database, and then add the print script / confirm dialog on page load using Page.ClientScript.RegisterStartupScript()
Note I don't recommend to embed the script in your C# code, so I'd suggest to take your confirmAction() function and place it (if not already) into a separate "yourScripts.js" file and then just call the function name when the page is loaded using jQuery. Here's an example:
In your master page or page header: This file should contain the confirmAction() function
<script type="text/javascript src="path/to/yourScriptsFile.js">
Then, in code-behind:
protected void Page_Load(object sender, EventArgs e)
{
// Only display script on PostBack, not initial page load
if (IsPostBack)
{
Page.ClientScript.RegisterStartupScript(
this.GetType(),
"confirmAction",
#"<script type=""Text/Javascript"">$(document).ready(function() { confirmAction('printable'); });</script>");
}
}
Also note, since you will NOT want a postback now, the confirmAction function should no longer return true; or use the trick code I posted above, and will just return false:
function confirmAction(printable) {
var r = confirm("You want to Print Invoice?");
if (r == true) {
var printContents = document.getElementById(printable).innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
}
return false;
}

Using onClientClick and onClick together with form submission

So I'm having some trouble. Even after trying many different solutions my problem is still persistent.
The button click will fire the java script code, but not the server side code.
<asp:Button ID="btnSubmit" runat="server" CssClass="ins_sub_btn_form_map" OnClientClick="javascript: stripeSubmit(); return true;" onClick="btnSubmit_Click"
UseSubmitBehavior="false" ValidationGroup="Submit" Text="Submit" />
here's my javascript:
function stripeResponseHandler(status, response) {
if (response.error) {
// show the errors on the form
$(".payment-errors").html(response.error.message);
} else {
var form$ = $("#form1");
// token contains id, last4, and card type
var token = response['id'];
// insert the token into the form so it gets submitted to the server
form$.append("<input type='visible' id='stripeToken' name='stripeToken' value='" + token + "' />");
// and submit
form$.get(0).submit();
}
}
function stripeSubmit() {
Stripe.setPublishableKey($("input#txtStripePK").val());
var expDate = $("input#txtExpirationDate").val();
if (Stripe.card.validateCardNumber($("input#txtCreditCardNumber").val()) == false)
{
alert("Credit Card Number Error");
return;
}
if (Stripe.card.validateCVC($("input#txtCVVNumber").val()) == false) {
alert("CVN Number Error");
return;
}
if (Stripe.card.validateExpiry((expDate.slice(0, 2)) , ("20" + expDate.slice(2, 4))) == false) {
alert("Expiration Date Error");
return;
}
// createToken returns immediately - the supplied callback submits the form if there are no errors
Stripe.card.createToken({
number: $("input#txtCreditCardNumber").val(),
cvc: $("input#txtCVVNumber").val(),
exp_month: (expDate.slice(0, 2)),
exp_year: ("20" + expDate.slice(2, 4))
}, stripeResponseHandler);
//return true; // submit from callback
}
I've tried it without the return true in javascript, with it in javascript. Also tried it without the return true in the onClientClick, also without the "javascript:". Literally everything I can think of.
Any help is appreciated. Thanks in advance.
If I'm not mistaken, by default, asp control's UseSubmitBehavior property is set to true. This means any event performed on that control will cause a postback. You have UseSubmitBehavior set to false so the code behind will never get executed since no postback occurs. When using OnClientClick() and OnClick() together, the client side code will execute first and then the server side code. Hope this helps
Use closing () on the method inside your Onclick. ex onClick="SomeMethod()"

Sometimes imagebutton click event not fired

I have a method that add's an onclick event too an imagebutton.
But sometimes you have to press the button multiple times before the "pop-up" window opens.
Any idea why this happens?
this is my code were I add the event to my imagebutton:
private void AddProjectDetails()
{
ImageButton imgBtn;
HiddenField hfld;
String ProjectNumber;
for (int i = 0; i < GridViewProperties.Rows.Count; i++)
{
hfld = GridViewProperties.Rows[i].FindControl("HiddenProjId") as HiddenField;
imgBtn = GridViewProperties.Rows[i].FindControl("ibtnShowExtra") as ImageButton;
ProjectNumber = hfld.Value;
imgBtn.Attributes.Add("onclick", "window.open('ProjectDetails.aspx?ProjectNumber=" + Server.UrlEncode(ProjectNumber) + "','Graph','height=590,width=600,left=50,top=50,scrollbars=yes'); return true;");
}
}
Try returning false from the javascript. This will prevent postback. Some times the postback can be faster then the windows.open, and in this case I don't think you want it.
Another solution is using an <a href='...' >image</a> instead of the imagebutton
Why are you using return true inside you java-script function.
Do you need postback on your page.
If not use return false.
I will also suggest you to write a javascript function and call it as follows
function OpenPopUp(projectNumber)
{
window.open("ProjectDetails.aspx?ProjectNumber="+ projectNumber
,'Graph','height=590,width=600,left=50,top=50,scrollbars=yes');
return false;
};
and call it inside your c# code
imgBtn.Attributes.Add("onclick", "return OpenPopUp('"+Server.UrlEncode(ProjectNumber)+"');");
Like Stefano and Shekhar said, you must not use return true for LinkButtons, Imagebuttons, unless you want the page post back.
You can also use this way:
<asp:ImageButton ID="ButtonOpenProject" runat="server" ImageUrl="~/Images/OpenProject.png" OnClientClick="return OpenProject('"<%# ProjectNumber %>"');" />
And in your JavaScript script you do something like this:
function OpenProject(ProjectNumber){
window.open('ProjectDetails.aspx?ProjectNumber=' + ProjectNumber + ','Graph','height=590,width=600,left=50,top=50,scrollbars=yes');
return false;
}
Hope this help.

How To set Default Button for ENTER key

We are using Sharepoint 2007 In which on master page we have Asp Image button. We want to set this image button as default button for enter key press. We tried some ways but not getting success.
Turned out more complicated than I thought but possible nonetheless. First of all, make sure the ID of your control is static:
<asp:ImageButton runat="server" ID="MyImageButton" ClientIDMode="Static" ImageUrl="pic.gif" OnClick="ImageButtonClicked" />
Now what you need is the following JavaScript code in your .aspx or .master page:
<script type="text/javascript">
var DEFAULT_BUTTON_ID = "MyImageButton";
// Mozilla, Opera and webkit nightlies currently support this event
if (document.addEventListener) {
// A fallback to window.onload, that will always work
window.addEventListener("load", HandleDefaultButton, false);
// If IE event model is used
} else if (document.attachEvent) {
// A fallback to window.onload, that will always work
window.attachEvent("onload", HandleDefaultButton);
}
function HandleDefaultButton() {
var inputs = document.getElementsByTagName("input");
//attach event for all inputs
for (var i = 0; i < inputs.length; i++) {
var input = inputs[i];
//maybe already got handler so add instead of override
if (document.addEventListener)
input.addEventListener("keypress", InputElement_KeyPressed, false);
else if (document.attachEvent)
input.attachEvent("onkeypress", InputElement_KeyPressed);
}
}
function InputElement_KeyPressed(evt) {
if (DEFAULT_BUTTON_ID && DEFAULT_BUTTON_ID.length > 0) {
//old IE event module
if (typeof evt == "undefined" || !evt)
evt = window.event;
var keyCode = evt.keyCode || evt.which;
if (keyCode === 13) {
var oButton = document.getElementById(DEFAULT_BUTTON_ID);
if (oButton) {
oButton.click();
return false;
} else {
alert("---DEBUG--- default button is defined but does not exist (" + DEFAULT_BUTTON_ID + ")");
}
}
}
return true;
}
</script>
You just need to define the real ID as the value of DEFAULT_BUTTON_ID and the code will automatically attach keypress event to all inputs (text, checkbox and radio) and when Enter is pressed, the button defined as default will get clicked.
As you're using SharePoint is means window.onload is already in use so we must add our own event not override it.
You can set the DefaultButton property to the id of the button you want to be default in the form tag.

Delete does not ask for confirmation

When Delete button is clicked, the confirmation box should pop up if the selected node has child nodes. Otherwise, it should not do anything.
Right now, when I click on delete, it just deletes without confirming.
Here is the code:
<asp:Button ID="btn_delete" runat="server" Height="32px"
onclick="btn_delete_Click" OnClientClick = "return childnode();"
Text="Delete" Visible="False" />
<script type="text/javascript">
function childnode() {
var treeViewData = window["<%=nav_tree_items.ClientID%>" + "_Data"];
var selectedNode = document.getElementById(treeViewData.selectedNodeID.value);
if (selectedNode.childNodes.length > 0) {
return confirm("heloo");
}
return false;
}
</script>
You'll need to return false from the function if you don't want the button push to go through in some cases. Currently you are only returning a value from the function when calling confirm.
If one or both of the if conditions fail, add a return false if you don't want the event to bubble up activating the button/sending the form.
Modification of your existing code
function childnode() {
var treeViewData = window["<%=nav_tree_items.ClientID%>" + "_Data"];
if (treeViewData.selectedNodeID.value != "") {
var selectedNode = document.getElementById(treeViewData.selectedNodeID.value);
if (selectedNode.childNodes.length > 0) {
return confirm("heloo");
}
return false; // don't send form
}
return false; // don't send form
}
Is it still malfunctioning?
Make sure that the logic inside your function is accurate, webbrowsers will often fail silently when trying to get a property of an undefined variable.
In your definition of your button you have written OnClientClick = "return childnode();", try changing this to OnClientClick="return childnode();" and see if that might solve the problem.
See if the event fires at all, OnClientClick="alert(123);".
Your function have return not in all of it's parts. Probably your function exists without confirm. Review your logic and decide what you want to do if one of your if statements not passed.
Change this:
onclick="btn_delete_Click" OnClientClick = "return childnode();"
To this:
onclick="btn_delete_Click;return childnode();"

Categories

Resources