OnClick/OnClientClick event with Asp.Net - javascript

I am a little confused to use this script and how it actually works?
Here is my script:
<script type="text/javascript">
$(document).ready(function () {
$('#<%=TextBox1.ClientID%>').change(function () {
$('#various3').attr('href', $(this).val());
});
$("#<%=Button1.ClientID%>").click(function (event) {
setTimeout(showStickySuccessToast, 1000);
function showStickySuccessToast() {
$().toastmessage('showToast', {
text: 'Finished taking Screenshot!',
sticky: false,
position: 'middle-center',
type: 'success',
closeText: '',
close: function () {
}
});
}
})
});
</script>
This is my button:
<a id="various3" href="#"><asp:Button ID="Button1" runat="server"
Text="Button" OnClientClick="Button1_Click"/></a>
This is my code behind for button1_Click event:
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim NewTh As New Threading.Thread(AddressOf DoIT)
NewTh.SetApartmentState(Threading.ApartmentState.STA)
NewTh.Start()
ImgPreview.ImageUrl = "~/uploads/Sample.jpg"
End Sub
Now if I click the button it should open the iframe and display the message which I am able to do.
Now the problem is how do I call the button1_Click event which is in the codebehind at the same time.
I have used OnClick and OnClientClick event as shown below but it's not working and I'm not getting any errors.

It looks like you've got things backwards:
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" />
The above example assumes that Button1_Click is the code-behind click event handler. Since you're assigning the client click event in jQuery, you shouldn't need to use OnClientClick at all.
EDIT
I would check to make sure that validation isn't intefering with the click. You can test this by setting CausesValidation="false" on the Button.

Onclick = raises a postback, executing the server eventhandler.
OnClientClick = raises a client click event and you can call a javascript function but you cant handlé an asp event directly although after calling a javascript function a postback occurs.

Related

How to execute click event of an asp.net button based upon the return value of OnClientClick event

I am working on an asp.net web forms project. I have an asp.net button which has both OnClientClick and onClick events. The OnClientClick event executes the javascript function processHolidayDates() which in turn shows a Telerik's Ok/Cancel message box. When the Ok button is clicked it will return true and if the Cancel button is clicked it will return false. So, when false is returned, I don't want the button click event to execute the server side code. However, the moment the message box is displayed already the code behind under the btnCreate_Click is executed. When I add "return false;" at the OnClientClick as in "OnClientClick="javascript:processHolidayDates(); return false " , the code behind is never executed even if I chose Ok in the message box. The following is my code on the aspx page
<asp:button id="btnCreate" runat="server" Text="Create" OnClientClick="javascript:processHolidayDates(); " onclick="btnCreate_Click"></asp:button>
function processStartAndEndDates() {
var oConfirm = radconfirm('Hello', callBackFn, 400, 300, null, 'Test');
return oConfirm ;
}
You could change your OnClientClick to
OnClientClick="return processHolidayDates();"
So that you will return false (and cancel the postback) if the user cancels the window.
This should work:
OnClientClick="return processHolidayDates();"

Prevent LinkButton post back OnClientClick not working. Why?

I know there are plenty of answers surrounding this topic but I just cannot get this to work.
I need to prevent a link button posting back and the following code is not working. The code is definitely being hit in all the required places.
Link button definition:
<asp:LinkButton ID="NavHelp" OnClientClick="showConfirm(event);" OnClick="NavHelp_Click" ToolTip="Help" runat="server"></asp:LinkButton>
Javascript function (definitely being hit)
function showConfirm(event) {
event.stopPropagation();
return false;
}
However after showConfirm returns false the link button still posts back to the server side NavHelp method.
As a side note, I also put a breakpoint in the __doPostback method generated by .NET and it does get hit after showConfirm returns false.
Can anyone shed any light on this?
Right, figured it out. I needed to include the return statement in the OnClientClick attribute:
OnClientClick="return showConfirm(event);"
NOT
OnClientClick="showConfirm(event);"
incidentally, you can use your original code, but rather than using event.stopPropagation() you can use event.preventDefault()
so your code would be
<asp:LinkButton ID="NavHelp" OnClientClick="showConfirm(event);" OnClick="NavHelp_Click" ToolTip="Help" runat="server"></asp:LinkButton>
function showConfirm(event) {
event.preventDefault();
return false;
}
read some more on event.preventDefault() vs event.stopPropagation()
here : http://davidwalsh.name/javascript-events
basically the preventDefault prevents the elemnt from carrying out its dfault action, i.e. visting a link or submitting a form, while stoppropagation allows the dfault action to occur, BUT doesn't inform any parent elements that it has happened.
i created a little jsfiddle : http://jsfiddle.net/XgSXr/ that shows you the prevent default, this should allow you to put in your own javascript logic, display modals etc, before successfully pushing through the link click.
This works:
<asp:LinkButton ID="NavHelp" ClientIDMode="Static" OnClientClick="showConfirm(event);" OnClick="NavHelp_Click" ToolTip="Help" runat="server"></asp:LinkButton>
<script>
$("#NavHelp").click(function(event) {
if (showConfirm()) {
event.stopPropagation();
event.preventDefault();
return false;
}
return true;
});
</script>
Add Return statement in onClientClick Javascript Event
OnClientClick="return showConfirm(event);"
So when showConfirm return false then request will not be transer to server and page not postback.

How to prevent ASP:Button from posting back from a jQuery click handler

I have an ASP:Button on a page. It renders as HTML like so:
<input type="submit" name="myButton" value="Do something"
onclick="javascript:WebForm_DoPostBackWithOptions(
new WebForm_PostBackOptions('myButton', '', true, '', '', false, false))"
id="myButton" />
Now I am trying to prevent the default behavior of this button (submitting the form) via a jQuery event handler:
$('#myButton').click(function () {
// do some client-side stuff
if (someCondition) {
// don't postback!
return false;
}
});
The problem here is that the inline click handler that ASP sticks on the input seems to be executing before the jQuery event handler, every time.
The easiest solution here would be to use a plain input type="button" instead of an ASP:Button, unfortunately this is not a possibilty as this ASP:Button does many other things that are required in this scenario.
What would be the best way to prevent the form submission from happening? I've thought of using string manipulation to prepend my handler on the element's onclick attribute, but this seems really dirty. I'd also like to avoid using the OnClientClick as this would require my handler function to be publicly exposed. Is there a better way?
Have you tried adding OnClientClick="return false;" attribute to your aspx button control?
No worries check out this post it provides a javascript event unloader script: Is it possible to remove all event handlers of a given element in javascript?
I think youre interested in the last method DomLib.prototype.removeEventsByTypeEx
I just found a way
<script type="text/javascript" src="Scripts/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
$(function () {
var ploopButton = null;
$("#ploop").click(function (e) {
ploopButton = this;
});
$("#form1").submit(function (e) {
if (ploopButton !== null) {
ploopButton = null;
return confirm('are u sure?');
}
return true;
});
});
</script>
<form id="form1" runat="server">
<asp:Button ID="ploop" Text="ploop" runat="server" OnClick="ploop_Click" />
</form>
Basically you would use a global flag indicating which button was clicked, and you would confirm the form submit when the flag is turned on

Disable Button placed inside an ASP.NET template upon click using Javascript

I hava an ASP.NET Web Forms application.
My goal is to disable the submit button btnFinish upon user click, in order to avoid multiple submits.
<asp:Button ID="btnFinish" runat="server" Text="Finish" UseSubmitBehavior="false"
CausesValidation="true" CommandName="MoveComplete" CssClass="buttonStyle"/>
The Javascript function is:
function Validate(btnFinishId) {
btnObj = document.getElementById(btnFinishId)
if (Page_IsValid) {
btnObj.disabled = true
}
else {
alert('Page has some validation error');
}
// this is to prevent the actual submit
e.preventDefault();
return false;
};
btnFinish is placed within a FinishNavigationTemplate in a ASP.NET Wizard Control.
Therefore, in order to avoid runtime errors, I need to get the ClientID of the control programmatically and then add it to the OnClientClick event of the button:
Button btFinish = MyWizard.FindControl("FinishNavigationTemplateContainerID$btnFinish") as Button;
if (btFinish != null){
btFinish.Attributes.Add("onclientclick", "Validate('" + btFinish.ClientID + "');");
}
But it does not work. I use Firebug to check the page rendered by the browser but although the source code looks perfect, upon click the Javascript function is not executed.
If in the Javascript function I replace Validate(btnFinishId) with Validate() and instead of using the code behind to add the OnClientClick I write:
<asp:Button OnClientClick="Validate();" "ID="btnFinish" runat="server" Text="Finish" UseSubmitBehavior="false"
CausesValidation="true" CommandName="MoveComplete" CssClass="buttonStyle"/>
The function is executed but of course does not do what I want, because the button Id is missing. Anybody has a solution?
You're on the right track. Something like this should work:
<script type="text/javascript">
validate = function(btn){
//trigger client-side validation
var valid = Page_ClientValidate("");
//disable the button if the form is valid
btn.disabled = valid;
//trigger postback if the form is valid
//otherwise do nothing
return valid;
}
</script>
<asp:Button ID="btnFinish" runat="server" Text="Finish" OnClientClick="return validate(this);" OnClick="btnFinish_Click" ... />
It looks kind of backwards, but you could shorten the function like this:
<script type="text/javascript">
validate = function(btn){
btn.disabled = Page_ClientValidate("");
return btn.disabled;
}
</script>
One way is to create a normal HTML button on your page, add attach a click event with jQuery.
You can then hide the .net button using css.
In the click event for your html buttom, you can all the .net buttons click event.
$("#yourbutton").trigger("click");

Firing the OnClick function of an asp:Button from calling .click()

I'd like to call some server-side code from a Javascript function.
I have this button:
<asp:Button ID="quickAdd" runat="server" text = "Quick add" OnClick="QuickAdd" />
If I click it, the C# function QuickAdd is called as expected
I have this command in a javascript function:
document.getElementById("quickAdd").click();
and the execution of this function does nothing. No error, I assume it simply clicks the button but this doesn't cause trigger the event necessary for the QuickAdd C# function to fire.
How do I get around this?
instead
document.getElementById("quickAdd").click();
use
document.getElementById('<%= quickAdd.ClientID %>').click();
where the quickAdd is actually the code name of your button variable. This is only because you will not be able to reference that html item because at runtime ID will change due to runat="server" - so this is only partial answer
Specifically you should try the .onclick() method however a more thorough treatment of the matter is given here:
Is it possible to trigger a link's (or any element's) click event through JavaScript?
you have 2 ways.
you can forget the QuickAdd server event and make an ajax call (see here how can this be done)
you can use the ASP.NET AJAX call to perform a Post, just hover the mouse in your link and see the javascript that will be executed, copy and use that method instead .click()
the .click() is not native in Javascript (it is in jQuery). So, when you call .click(), nothing is going to happen, as .click() isn't specificed.
If you would like to get the onclick method for your object, use the following code:
var func = document.getElementById("quickAdd").onclick;
At this point, func is the onclick function of your #quickAdd element. So, at this point, you can call:
func();
or
document.getElementById("quickAdd").onclick();
Either of those will get and execute your onclick event.
If this doesn't help, pull up your page in Firefox and execute your javascript with the Firebug console (Firebug is a Firefox plugin that you can install, and it gives you access to the ).
$(document).ready(function () {
$('#btnCancel').click(function (e) {
e.preventDefault();
$("<div><span><b>Are you sure you want to cancel this order?</b></span></div>").dialog({
modal: true,
draggable: false,
resizable: false,
width: 430,
height: 150,
buttons: {
"No": function () {
$(this).dialog("destroy");
},
"Yes": function () {
$("#btnCancel").unbind();
$(this).dialog("destroy");
document.getElementById('<%= btnCancel.ClientID %>').click();
}
}
});
});
});
Then in the Body
<asp:button id="btnCancel" runat="server" cssclass="button_major" text="Cancel" style="float: right"
onclick="btnCancel_ClickEvent" clientidmode="Static" />

Categories