Button's .click() command not working in Chrome - asp.net

I have a button
<asp:Button ID="submitRegionsButton" runat="server" Text="OK" OnClick="OnSubmitRegion" />
and when I click it, everything works as expected, however when I have a javascript function call it using btn.click(), the click command is not executed. The button is found properly but just doesn't then work or run the OnClick function in my code behind
Any ideas? It works in IE, haven't tested firefox though
Okay, tested in firefox, doesn't work there. Everything works right up until the actual call to .click(), no idea why :/
Code that calls the click:
function dropDownProductBlur() {
if (isItemClicked) {
var combo = $find("<%= productDropDown.ClientID %>");
var btnSubmitProd = $get(combo.get_id() + "_Footer" + "_submitProductsButton");
if (btnSubmitProd)
btnSubmitProd.click();
}
}
Just for understanding, the button is contained within a dropdown, and when the dropdown closes, it "clicks" the button (or, well, is supposed to..) clicking the button manually works, and the find works and finds the button properly.

I recently ran into this problem myself. I believe the issue is that in javascript, this .click() is either treated as the component's onClientClick event, or something else entirely. Not sure on this.
In any case, my solution:
Instead of calling btnSubmitProd.click(), do __doPostBack('Foo', 'Bar'); where Foo is an arbitrary name (typically the component, so "submitRegionButton") and Bar is an arbitrary value for that name, typically the event (so "click") (also, there are TWO underscores there, not one). Then, in your codebehind:
try {
if (Request["__EVENTTARGET".ToString() == "Foo" && Request["__EVENTARGUMENT"].ToString() == "Bar" {
//call the codebehind directly here
OnSubmitRegion(null null);
}
}
I assume your codebehind function is of the form protected void OnSubmitRegion(object sender, EventArgs e). If you need the values for any of those variables, things get a little more complicated. If not, give the above a try.

Related

How to set UseSubmitBehavior="False" in one place for the whole web application

I want all of the buttons in my asp.net web forms application to have UseSubmitBehavior="False" but I don't want to go through all my pages trying to hunt down each and every last button and set the property individually.
I am hoping there is a way to do this globally, for example in the web.config file. Thanks!
This is not a page property or something like that
this is a button property which allowes submit via __doPostBack
You Can't do this globally via web.config ( or in any other way).
The reason for wanting to set UseSubmitBehavior="False" is to stop the form from submitting when the user presses enter. If this is your goal then the following will interest you:
Another way to do this is to use JavaScript. This shifts the overhead of MikeSmithDev's suggestion to the client which might be more acceptable depending on your scenario.
Please note that the following JavaScript makes use of the jQuery library:
$(document).ready(function () {
preventSubmitOnEnter();
});
function preventSubmitOnEnter() {
$(window).keypress(function (e) {
if (e.which == 13) {
var $targ = $(e.target);
if (!$targ.is("textarea") && !$targ.is(":button,:submit")) {
return false;
}
}
});
}

How can I execute JavaScript from my code-behind after my UpdatePanel has finished loading its DOM elements?

I have an UpdatePanel with a repeater in it that is re-bound after a user adds an item to it via a modal popup.
When they click the button to add a new row to the repeater the code-behind looks something like this:
protected void lbtnAddOption_Click(object sender, EventArgs e)
{
SelectedOption = new Option()
{
Account = txtAddOptionAccountNumber.Text,
Margin = chkAddOptionMargin.Checked,
Symbol = txtAddOptionSymbol.Text,
Usymbol = txtAddOptionUsymbol.Text,
};
Presenter.OnAddOption(); // Insert the new item
RefreshOptions(); // Pull down and re-bind all the items
mpeAddOptionDialog.Hide(); // Hide the modal
// ... Make call to jQuery scrollTo() method here?
}
This works fine and the new row will show up quickly via the UpdatePanel.
However, there are often hundreds of rows and where the new one is added is based on the current sorting column used.
So, I wanted to take this as a chance to use the sweet jQuery ScrollTo plugin. I know that if I give it the ID of my overflowed container div and the ID of an element within it, it will smoothly scroll straight to the users newly added row.
However, there are two problems:
I need to find the appropriate row so I can snag the ClientID for it.
I need to execute the jQuery snippet from my code-behind that will cause my newly updated repeater to scroll to the right row.
I've solved #1. I have a reliable method that will produce the newly added row's ClientID.
However, problem #2 is proving to be tricky. I know I can just call ScriptManager.RegisterStartupScript() form my code-behind and it will execute the JavaScript on my page.
The problem I'm having is that it seems that it is executing that piece of JavaScript before (I'm guessing) the newly refreshed DOM elements have fully loaded. So, even though I am passing in the appropriate jQuery line to scroll to the element I want, it is erroring out for me because it can't find that element yet.
Here is the line I'm using at the end of the method I posted above:
string clientID = getClientIdOfNewRow();
ScriptManager.RegisterStartupScript(this, typeof(Page), "ScrollScript", String.Format("$(\"#optionContainer\").scrollTo(\"{0}\", 800);", clientID), true);
What do I need to do so I can ensure that this line of JavaScript isn't called until the page with the UpdatePanel is truly ready?
If the stuff you need to process is in the update panel, then you need to run your JS once that panel is loaded. I use add_endRequest for that. This below is hacked from something rather more complex. It runs once on document ready, but installs the "end ajax" handler which is triggered every time your update panel is updated. And by the time it fires, it's all there for you.
var prm = Sys.WebForms.PageRequestManager.getInstance();
jQuery(document).ready(function () {
prm.add_endRequest(EndRequestHandler);
});
function EndRequestHandler(sender, args) {
// do whatever you need to do with the stuff in the update panel.
}
Obviously you can inject that from code-behind if you want.
You can use the Sys.Application.load event which is raised after all scripts have been loaded and the objects in the application have been created and initialized.
So your code would be:
string clientID = getClientIdOfNewRow();
ScriptManager.RegisterStartupScript(this, typeof(Page)
,"ScrollScript"
,String.Format("Sys.Application.add_load(function(){{$(\"#optionContainer\").scrollTo(\"{0}\", 800);}});"
, clientID)
, true);

How do I interrupt an ASP.NET button postback with BlockUI and Jquery

I have an ASP.NET page with a number of ASP:Button instances on it. For some, I need to show a confirmation prompt and, should the user choose yes, the original postback method is called. Otherwise, the overall process is cancelled.
I've got an example running but I get inconsistent results, mainly in FF3 where I get an exception thrown:
[Exception... "Illegal operation on WrappedNative prototype object" nsresult: "0x8057000c (NS_ERROR_XPC_BAD_OP_ON_WN_PROTO)" location: "JS frame ::
I've looked this error up but I'm drawing a loss as to where I'm going wrong. Here's my example case. Note, for now I'm just using the css class as a lookup. Longer term I can embed the clientID of the control into my JS if it proves necessary :).
Html fragment:
<asp:Button ID="StartButton" runat="server" CssClass="startbutton" Text="Start" OnClick="OnStartClicked" />
Javascript:
$(".startbutton").each(function(){
$(document).data("startclick", $(this).get()[0].click);
$(this).unbind("click");
}).click(function(){
var oldclick = $(document).data("startclick");
alert("hello");
try
{
oldclick();
}
catch(err)
{
alert(err);
alert(err.description);
}
return false;
});
My code behind is relatively simple, the OnStart method simply executes a Response.Write
I've only just started looking into bind, unbind and trigger so my usage here is pretty much 'first time'.
Thanks for any help or advice.
S
EDIT:
This describes what I'm trying to do and also gives a run down of the kind of pitfalls:
http://www.nabble.com/onClick-prepend-td15194791s27240.html
How about this?
$(document).ready( function() {
$('.startbutton').click(function() {
return confirm('Are you sure?');
})
});
I've solved my problem for IE7 and FF3.
The trick is to make the postback work as an 'onclick' via an ASP.NET attribute on the button (see below). In Javascript this gets pulled out as a function reference when you read the click in JQuery.
To make it work, you then clear the onclick attribute (after saving it) and call it later on.
My code below shows it in action. This code isn't complete as I'm part way through making this into a generic prompt for my application. Its also a bit badly laid out! But at least it shows the principle.
ASP.NET button
<asp:Button ID="StartButton" runat="server" CssClass="startbutton" Text="Start" OnClick="OnStart" UseSubmitBehavior="false" />
Javascript:
$(".startbutton").each(function(){
$(document).data("startclick", $(this).attr("onclick"));
$(this).removeAttr("onclick");
}).click(function(){
$.blockUI({ message: $('#confirm'), css: { width: '383', cursor: 'auto' } });
$("#yes").click(function(){
$.unblockUI();
var oldclick = $(document).data("startclick");
try
{
oldclick();
}
catch(err)
{
alert(err);
alert(err.description);
}
});
$("#no").click(function(){
$.unblockUI();
});
return false;
});
Your problem comes from here :
$(document).data("startclick", $(this).get()[0].click);
...
var oldclick = $(document).data("startclick");
...
oldclick();
Here, you try to intercept a native event listener but there are two errors :
Using unbind will not remove the native event listener, just the ones added with jQuery
click is, AFAIK, a IE only method used to simulate a click, it not the event handler itself
You'll have to use onclick instead set its value to null instead of using unbind. Finally, don't store it in $(document).data(...), you'll have some problems when you add other buttons. Here is a sample code you can use :
$("selector").each(function()
{
var oldclick = this.onclick;
this.onclick = null;
$(this).click(function()
{
if (confirm("yes or no ?")) oldclick();
});
});
for mi works:
this.OnClientClick = "$.blockUI({ message: $('#ConfirmacionBOX'), css: { width: '275px' } });return false;";
This is a button (is a button class)

Programmatically triggering events in Javascript for IE using jQuery

When an Event is triggered by a user in IE, it is set to the window.event object. The only way to see what triggered the event is by accessing the window.event object (as far as I know)
This causes a problem in ASP.NET validators if an event is triggered programmatically, like when triggering an event through jQuery. In this case, the window.event object stores the last user-triggered event.
When the onchange event is fired programmatically for a text box that has an ASP.NET validator attached to it, the validation breaks because it is looking at the element that fired last event, which is not the element the validator is for.
Does anyone know a way around this? It seems like a problem that is solvable, but from looking online, most people just find ways to ignore the problem instead of solving it.
To explain what I'm doing specifically:
I'm using a jQuery time picker plugin on a text box that also has 2 ASP.NET validators associated with it. When the time is changed, I'm using an update panel to post back to the server to do some things dynamically, so I need the onchange event to fire in order to trigger the postback for that text box.
The jQuery time picker operates by creating a hidden unordered list that is made visible when the text box is clicked. When one of the list items is clicked, the "change" event is fired programmatically for the text box through jQuery's change() method.
Because the trigger for the event was a list item, IE sees the list item as the source of the event, not the text box, like it should.
I'm not too concerned with this ASP.NET validator working as soon as the text box is changed, I just need the "change" event to be processed so my postback event is called for the text box. The problem is that the validator throws an exception in IE which stops any event from being triggered.
Firefox (and I assume other browsers) don't have this issue. Only IE due to the different event model. Has anyone encountered this and seen how to fix it?
I've found this problem reported several other places, but they offer no solutions:
jQuery's forum, with the jQuery UI Datepicker and an ASP.NET Validator
ASP.NET forums, bug with ValidatorOnChange() function
I had the same problem. Solved by using this function:
jQuery.fn.extend({
fire: function(evttype){
el = this.get(0);
if (document.createEvent) {
var evt = document.createEvent('HTMLEvents');
evt.initEvent(evttype, false, false);
el.dispatchEvent(evt);
} else if (document.createEventObject) {
el.fireEvent('on' + evttype);
}
return this;
}
});
So my "onSelect" event handler to datepicker looks like:
if ($.browser.msie) {
datepickerOptions = $.extend(datepickerOptions, {
onSelect: function(){
$(this).fire("change").blur();
}
});
}
I solved the issue with a patch:
window.ValidatorHookupEvent = function(control, eventType, body) {
$(control).bind(eventType.slice(2), new Function("event", body));
};
Update: I've submitted the issue to MS (link).
From what you're describing, this problem is likely a result of the unique event bubbling model that IE uses for JS.
My only real answer is to ditch the ASP.NET validators and use a jQuery form validation plugin instead. Then your textbox can just be a regular ASP Webforms control and when the contents change and a postback occures all is good. In addition you keep more client-side concerns seperated from the server code.
I've never had much luck mixing Webform Client controls (like the Form Validation controls) with external JS libraries like jQuery. I've found the better route is just to go with one or the other, but not to mix and match.
Not the answer you're probably looking for.
If you want to go with a jQuery form validation plugin concider this one jQuery Form Validation
Consider setting the hidden field _EVENTTARGET value before initiating the event with javascript. You'll need to set it to the server side id (replace underscore with $ in the client id) for the server to understand it. I do this on button clicks that I simulate so that the server side can determine which OnClick method to fire when the result gets posted back -- Ajax or not, doesn't really matter.
This is an endemic problem with jQuery datepickers and ASP validation controls.
As you are saying, the wrong element cross-triggers an ASP NET javascript validation routine, and then the M$ code throws an error because the triggering element in the routine is undefined.
I solved this one differently from anyone else I have seen - by deciding that M$ should have written their code more robustly, and hence redeclaring some of the M$ validator code to cope with the undefined element. Everything else I have seen is essentially a workaround on the jQuery side, and cuts possible functionality out (eg. using the click event instead of change).
The bit that fails is
for (i = 0; i < vals.length; i++) {
ValidatorValidate(vals[i], null, event);
}
which throws an error when it tries to get a length for the undefined 'vals'.
I just added
if (vals) {
for (i = 0; i < vals.length; i++) {
ValidatorValidate(vals[i], null, event);
}
}
and she's good to go. Final code, which redeclares the entire offending function, is below. I put it as a script include at the bottom of my master page or page.
Yes, this does break upwards compatibility if M$ decide to change their validator code in the future. But one would hope they'll fix it and then we can get rid of this patch altogether.
// Fix issue with datepicker and ASPNET validators: redeclare MS validator code with fix
function ValidatorOnChange(event) {
if (!event) {
event = window.event;
}
Page_InvalidControlToBeFocused = null;
var targetedControl;
if ((typeof (event.srcElement) != "undefined") && (event.srcElement != null)) {
targetedControl = event.srcElement;
}
else {
targetedControl = event.target;
}
var vals;
if (typeof (targetedControl.Validators) != "undefined") {
vals = targetedControl.Validators;
}
else {
if (targetedControl.tagName.toLowerCase() == "label") {
targetedControl = document.getElementById(targetedControl.htmlFor);
vals = targetedControl.Validators;
}
}
var i;
if (vals) {
for (i = 0; i < vals.length; i++) {
ValidatorValidate(vals[i], null, event);
}
}
ValidatorUpdateIsValid();
}
This is how I solved a simlar issue.
Wrote an onSelect() handler for the datepicker.
link text
In that function, called __doPostBack('textboxcontrolid','').
This triggered a partial postback for the textbox to the server, which called the validators in turn.

How to click a button on an ASP.NET web page programmatically?

I am trying to figure out how to click a button on a web page programmatically.
Specifically, I have a WinForm with a WebBrowser control. Once it navigates to the target ASP.NET login page I'm trying to work with, in the DocumentCompleted event handler I have the following coded:
HtmlDocument doc = webBrowser1.Document;
HtmlElement userID = doc.GetElementById("userIDTextBox");
userID.InnerText = "user1";
HtmlElement password = doc.GetElementById("userPasswordTextBox");
password.InnerText = "password";
HtmlElement button = doc.GetElementById("logonButton");
button.RaiseEvent("onclick");
This fills the userid and password text boxes fine, but I am not having any success getting that darned button to click; I've also tried "click", "Click", and "onClick" -- what else is there?. A search of msdn of course gives me no clues, nor groups.google.com. I gotta be close. Or maybe not -- somebody told me I should call the POST method of the page, but how this is done was not part of the advice given.
BTW The button is coded:
<input type="submit" name="logonButton" value="Login" onclick="if (typeof(Page_ClientValidate) == 'function') Page_ClientValidate(); " language="javascript" id="logonButton" tabindex="4" />
How does this work? Works for me
HtmlDocument doc = webBrowser1.Document;
doc.All["userIDTextBox"].SetAttribute("Value", "user1");
doc.All["userPasswordTextBox"].SetAttribute("Value", "Password!");
doc.All["logonButton"].InvokeMember("Click");
var btn = document.getElementById(btnName);
if (btn) btn.click();
There is an example of how to submit the form using InvokeMember here.
http://msdn.microsoft.com/en-us/library/ms171716.aspx
You can try and invoke the Page_ClientValidate() method directly through the clientscript instead of clicking the button, let me dig up an example.
Using MSHTML
mshtml.IHTMLWindow2 myBroserWindow = (mshtml.IHTMLWindow2)MyWebBrowser.Document.Window.DomWindow;
myBroserWindow.execScript("Page_ClientValidate();", "javascript");
Have you tried fireEvent instead of RaiseEvent?
You could call the method directly and pass in generic object and EventArgs parameters. Of course, this might not work if you were looking at the sender and EventArgs parameters for specific data. How I usually handle this is to refactor the guts of the method to a doSomeAction() method and the event handler for the button click will simply call this function. That way I don't have to figure out how to invoke what is usually just an event handler to do some bit of logic on the page/form.
In the case of javascript clicking a button for a form post, you can invoke form.submit() in the client side script -- which will run any validation scripts you defined in the tag -- and then parse the Form_Load event and grab the text value of the submit button on that form (assuming there is only one) -- at least that's the ASP.NET 1.1 way with which I'm very familiar... anyone know of something more elegant with 2.0+?
Just a possible useful extra where the submit button has not been given an Id - as is frequently the case.
private HtmlElement GetInputElement(string name, HtmlDocument doc) {
HtmlElementCollection elems = doc.GetElementsByTagName("input");
foreach (HtmlElement elem in elems)
{
String nameStr = elem.GetAttribute("value");
if (!String.IsNullOrEmpty (nameStr) && nameStr.Equals (name))
{
return elem;
}
}
return null;
}
So you can call it like so:
GetInputElement("Login", webBrowser1.Document).InvokeMember("Click");
It'll raise an exception if the submit input with the value 'Login', but you can break it up if you want to conditionally check before invoking the click.
You posted a comment along the lines of not wanting to use a client side script on #Phunchak's answer. I think what you are trying to do is impossible. The only way to interact with the form is via a client side script. The C# code can only control what happens before the page is sent out to the browser.
try this
button.focus
System.Windows.Forms.SendKeys.Send("{ENTER}")

Resources