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.
Related
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);
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.
I was attempt to wrap some simple logic into a javascript/jquery closure to bind a form to jQuery validate. The normal code looks like this ...
// attach the jquery unobtrusive validator
$.validator.unobtrusive.parse("#formName");
// bind the submit handler to unobtrusive validation.
$("#formName").data("validator").settings.submitHandler = function() {
viewModel.Save( $("#formName" ) );
};
Works wonderfully. I just wanted to wrap it and make it cleaner. So I wrote this.
(function ($){
$.fn.submitHandler = function(callback){
var container = $(this);
// attach the jquery unobtrusive validator
$.validator.unobtrusive.parse(container);
// bind the submit handler to unobtrusive validation.
$(container).data("validator").settings.submitHandler = callback(container);
return true;
};
})(jQuery);
So the inevitible goal is that I could just do this in the future.
$("#formName").submitHandler(function (e) {
viewModel.Save(e);
});
I know it seems silly, but I thought it was a good chance to learn more. I just recently learned about Javascript closures and wanted to try it out, and this felt like a good thing to test it on.
The problem is, if I make an HTML form and try to bind this to it, it does work like I want...but it works twice. First, the form just 'posts' when the page loads, then it does the behavior I want and expect after that.
Edit
When I say the form 'posts', I mean that the alert dialog in the Save function fires. There does not APPEAR to be any server-post back.
Here is the form I am using to test it on.
<form id="_formName" action="" method="post">
<input type="text" required="required" />
<button type="submit">Submit</button>
</form>
<script type="text/javascript">
var viewModel = {
Save: function ($form) {
alert($form.attr('id'));
}
};
$("#_formName").submitHandler(function (e) {
viewModel.Save(e);
});
</script>
I believe your problem is with this line:
// bind the submit handler to unobtrusive validation.
$(container).data("validator").settings.submitHandler = callback(container);
Here you are intending to assign a function reference to the "submitHandler" property... but, what you are actually doing, is calling the function "callback" with a parameter "container", and assigning the result of that evaluated expression to the "submitHandler" property... which, I don't believe you were intending to do.
You might try this instead (keep in mind, I really don't know the specifics of your situation, i'm just going off what I can deduce):
// bind the submit handler to unobtrusive validation.
$(container).data("validator").settings.submitHandler = function() { callback(container); };
I have a menu on my aspx page which looks beautiful. It's exactly what I need (found it here).
Problem that I have is this: I need (somehow) to kick off a button control from the javascript. I realize that in the example, the menu items are simply href links, but I'm wondering how I could possibly do a postback and kick off my Button1_OnClick event.
Any ideas?
Thanks,
Jason
Please note that Button1 is an ASP button, with server-side VB.NET code behind it
You'll need something like
__doPostBack(*Button1's clientId*,"OnClick") ;
Button1 will have a property called "ClientID". You can echo that out to the HTML code to get the object by document.getElementById("<%= Button1.ClientID %>"), and from there you only have to invoke the click like normally.
So:
document.getElementById("<%= Button1.ClientID %>").click();
As noted by a commentator, the .click() method won't work in all browsers. Here is one another way to click a button in JavaScript (should also work with links):
// Where 'button' is the value of the document.getElementById() function:
if (button.dispatchEvent) {
var e = document.createEvent(“MouseEvents”);
e.initEvent(“click”, true, true);
button.dispatchEvent(e);
}
else {
button.click();
}
The click() method of any <a> element simulates a click.
You could make your <a /> links, LinkButtons. You could alternativly keep your <a /> links and put runat="server" on them and that would do it without having to fire a separate button click.
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.