Stop onclick after onclientclick - javascript

I've seen a few examples on how to do this but they don't seem to be working for me. Having said that, I am doing it a little differently than the examples I've seen so I'm not sure if what I'm trying to do is possible.
I have a multiline asp texbox and onclientclick I want to make sure (among other things) the user hasn't gone over on max length before I submit the onclick event. However, this textbox is part of a user control that will be used X number of times on the page so I can't just grab the control from the Javascript. I have to send the clientID from the code behind. So I'm adding the OnClientClick event on the codebehind and pass the clientID for the control there. I wonder if that's why I'm getting the results I'm getting.
SaveNoteButton.OnClientClick = string.Format("return BeforeSave('{0}');", NoteTextBox.ClientID);
<asp:Button runat="server" CssClass="casenotes-bluebuttons" ID="SaveNoteButton" Text="Save" OnClick="SaveNoteButton_Click" Enabled="false" />
function BeforeSave(noteCtrl) {
var txt = document.getElementById(noteCtrl);
if (txt.value.length > 500) {
alert("false");
return false;
}
else {
alert("true");
return true;
}
}
So in theory, the OnClientClick property is added to the SaveNoteButton button. When it's fired, it passes the NoteTextBox.ClientID, the js checks the textbox length, returns true or false then the OnClick event fires depending on the return value. But it doesn't. I even tried wrapping the method call in an alert and the method is in fact returning what I expect but the OnClick event isn't firing regardless of the method's return value. I even tried removing the method call and hardcoding true and it still doesn't fire. So I know the return value is true and yet no OnClick love.

Oddly enough, it was syntax on the call to the js method.
SaveNoteButton.OnClientClick = string.Format("return BeforeSave('{0}');", NoteTextBox.ClientID);
becomes
SaveNoteButton.OnClientClick = string.Format("BeforeSave('{0}')", NoteTextBox.ClientID);
and it works just fine.

Remove the Enabled="false" bit. This is why the onclick event does not fire.

Alright, this is what I did to solve the problem:
SaveNoteButton.OnClientClick = string.Format("if(!BeforeSave('{0}', '{1}')) return false;", NoteTextBox.ClientID, this._maxLength);

Related

ASP.NET Button, OnClientClick not working

I have button with both OnClick and OnClientClick events declared.
There is some specific task that I wish to accomplish before the postback occurs but for some strange reason OnClientClick is never fired. I have used it numerous times before and never had this specific issue.
There is something wrong with it, I also tried with adding 'return false' directly to prevent server side processing but postback occurs nevertheless.
I checked whether my form is inside an UpdatePanel but it is not.
<cms:CMSButton ID="btnOk" OnClientClick="clientClick()" OnClick="btnOK_Click" runat="server" ButtonStyle="Default"
EnableViewState="false"></cms:CMSButton>
$(document).ready(function () {
function clientClick() {
console.log("Clicked");
document.getElementById("<%=spinner.ClientID %>").style.display = "block";
document.getElementById("<%= btnOk.ClientID%>").style.display = "none";
}
});
Also I tried firing the event in this manner, with no luck, so there may be something else going on here:
$('#<%=btnOk.ClientID%>').click(function () {
console.log('clicked');
});
Checked the console but could not find any js errors.
As others suggested - avoid document.Ready like the plague.
Now don't take this suggested rule as all or nothing. The simple matter is WHEN you need to use document.ready - then use it, but ALSO when you can avoid using it, don't just out of the blue use it to hook up event code - it REALLY hard to follow.
Now, you posted your markup - I don't know if you left parts out, but again WHEN code is not working, then you want to provide a wee bit more details.
your code should look like this:
<cms:CMSButton ID="btnOk" OnClientClick="clientClick()" OnClick="btnOK_Click"
runat="server" ButtonStyle="Default"
EnableViewState="false"></cms:CMSButton>
<script>
function clientClick() {
console.log("Clicked");
document.getElementById("<%=spinner.ClientID %>").style.display = "block";
document.getElementById("<%= btnOk.ClientID%>").style.display = "none";
}
</script>
So you have a function, you have a onclick, you have a js function wiht that name. Nice, simple code approach here. Be it code behind, or js code in the page? You write a function, and then specify that function. Keep this simple.
In fact, I often suggest that you put the RIGHT below the button so you don't have to go trouging around the page to go find that routine in the markup.

__doPostBack doesn't fire on the first click

Just like the title says. I have some javascript on a page that is supposed to fire a __doPostBack call if other variables/conditions on the form are valid.
function DoPostBack() {
var valid = true;
if (SomethingHappens) {
valid = false
}
alert("Is_Valid? " + valid) //evaluates to true
if (valid) {
__doPostBack("btnSubmit",''); //First click here does nothing, despite it being it by code. Works fine the second time.
}
And that is hooked up to a button as follows:
<input ID="btnSubmit" runat="server" onclick="DoPostBack();" type="button" value="Submit" style="width:80px"/>
What is causing the first click of the submit button to be ignored? I have confirmed that this is the behavior I am seeing by placing a breakpoint in my page_load event. The first time __doPostBack is called, the breakpoint is not hit, the second time, it is hit.
If what you are saying is correct, your function should get executed, since it is not, then at least something you have said is not true.

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.

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" />

Stopping form submit during onclick of an input type="image"

The reset action is performed by input type="image" and onclick calls a function called resetForm().
When reset is clicked the form submit should not happen. I tried returning false from resetForm() function and still it doesn't work. Please help me out.
Instead of returning false in resetForm, use preventDefault in the click function:
$('#myButton').click(function(event) {
event.preventDefault(); // yaa!
resetForm();
});
return false does also work, but when jQuery got a function for something, I usually stick with that.
I will make sure that your function is properly returning false, make sure you have no syntax error in your JavaScript.
Good way to test this, try alert("Testing Return!"); right before return false.
If you would like to use return False; as opposed to event.preventDefault();, you must put the return false within the event callback. So, it would need to be like this if you are returning false in resetForm():
$('#myButton').click(function() {
return resetForm();
});
Even simpler, if all you are doing is running a function on click (thanks to JimmyP for that reminder):
$('#myButton').click(resetForm);
In my opinion, it's cleaner, simpler, and involves less typing. All wins for me.
I think everyone else is describing a different way to do what I am suggesting which is:
onClick="return resetForm();"
Otherwise the onClick is calling without caring the return.
There is an actual way of doing it. But it requires a few steps.
Define your ..
You need bind the click even of the input item. use jquery to do it.
write your function
binding:
$(document).ready(function () {
$("#yourinputtypeid").on("click", {Parameter1 : "your parameter value"},
FunctionNameToRun);
}
the Function.
function FunctionNameToRun(event)
{
event.preventDefault();
// the rest of your code
}
That's it. This should prevent the submission / reloading of the page.
I would probably be better to use <input type="reset" /> rather than type="image", because the latter has the semantics of type="submit" and the former seems to have the semantics that you're going for. You could also easily put an image on such a button as well and it would probably save you the trouble of having to write a JavaScript function.
If you want to continue using <input type="image" />, I don't think returning false from the onclick event will do anything. Since it has the semantics of submitting the form, the form will just be submitted. In order to counter that, you could maybe place an onsubmit attribute in the form tag: <form onsubmit="return submitFunction();" />. In the submitFunction you could then check which submit/image button was pressed and depending on that return true or false. Returning false here will prevent the form from submitting.

Categories