Jquery datepicker popup not closing on select date in IE8 - asp.net

I've got a web form with a start date field. I've tied a jquery datepicker to the txt field. Now when I choose a date in FF, the selected date is populated in the text box and the calendar popup closes. However when I do the same thing in IE8, the selected date is populated in the text box but the popup remains open. I've also noticed that a script error is generated as soon as I select a date in the popup calendar.
I'm using jquery 1.3.2, jquery-ui 1.7.2, and .NET 3.5. Here's an example of my code:
<script type="text/javascript">
$(document).ready(function() {
$("#<%=txtStartDate.ClientID%>").datepicker({
changeMonth: true,
changeYear: true,
showButtonPanel: true,
showOn: 'button',
buttonImage: '/_layouts/images/CALENDAR.GIF',
buttonImageOnly: true
});
});
</script>
<div id="stylized">
<asp:ValidationSummary ID="vs" runat="server" CssClass="messages-error" HeaderText=" Action required before the form can be submitted." ForeColor="" ValidationGroup="sh" />
<div class="formrow">
<div class="ms-formlabel formlabel">
<asp:Label ID="lblStartDate" runat="server" CssClass="ms-standardheader" AssociatedControlID="txtStartDate">Start Date:</asp:Label>
</div>
<div class="ms-formbody formfield">
<asp:RequiredFieldValidator ID="reqStartDate" runat="server" ControlToValidate="txtStartDate" ErrorMessage="Start Date is a required field." Text="*" Display="Dynamic" ValidationGroup="sh"></asp:RequiredFieldValidator>
<asp:CompareValidator ID="cvStartDate" runat="server" ControlToValidate="txtStartDate" ErrorMessage="Date must be in the format MM/DD/YYYY" Text="*" Display="Dynamic" ValidationGroup="sh" Operator="DataTypeCheck" Type="Date"></asp:CompareValidator>
<asp:TextBox ID="txtStartDate" runat="server"></asp:TextBox>
<span class="formMessage">ex. MM/DD/YYYY</span>
</div>
</div>
<div id="buttonrow">
<asp:Button ID="btnSubmit" runat="server" Text="Submit" CssClass="ms-ButtonHeightWidth" OnClick="Submit_Click" ValidationGroup="sh" />
<asp:Button ID="btnCancel" runat="server" Text="Cancel" CssClass="ms-ButtonHeightWidth" OnClick="Cancel_Click" CausesValidation="false" />
</div>
</div>
Here's the script error I get in IE when I select the date:
'length' is null or not an object
WebResource.axd
Here's the code where the error is being thrown from:
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;
for (i = 0; i < vals.length; i++) {
ValidatorValidate(vals[i], null, event);
}
ValidatorUpdateIsValid();
}
It happens on the .length in the for loop at the end. Vals is null and isn't found in the previous if/else. I've stepped through the javascript and if (typeof(targetedControl.Validators) != "undefined") returns false and then if (targetedControl.tagName.toLowerCase() == "label") returns false too. Thus the length is null or not an object error.
Now I'm not sure if the datepicker popup not closing in IE and the script error in the WebResources.axd file are related errors, but I'm leaning that way. Can anyone tell me why the popup isn't closing?

As a date is selected, the datepicker triggers the change event on the INPUT element, but the ASP.Net validator picks up the click event instead, with the source an A element, and tries to find the validators on that A element, instead of the INPUT. This can be observed by inspecting event.srcElement inside the validator's ValidatorOnChange function. In browsers other than IE, event.type is 'change' and event.target is correctly the INPUT.
While the no-op function onSelect: function() { } prevents the error, by overriding the .change() built-in to the datepicker's default onSelect, it also prevents the validators from triggering. Here's a work-around for both:
onSelect: function() {
this.fireEvent && this.fireEvent('onchange') || $(this).change();
}
This uses the normal .change() trigger except on IE, where it's required to use .fireEvent to get the event object to be associated with the change and not the click.

It seems to be a bug of sorts, but adding this line in the datepicker declaration should solve it:
onSelect: function() {}

The solutions provided above only prevents the error from occurring.
On the datepicker:
onSelect : function(dateText, inst){ inst.input.trigger('cValidate')
and bind the event to the calendar input element.
.bind('cValidate', function (event) { window.ValidatorOnChange(event); });
this will fire the validatorchanged event with the correct event args (input field).

The reason
The root bug (I think it's probably meant to be a feature, or maybe a workaround for a known IE bug?) is in ASP.Net's ValidatorHookupEvent:
var func;
if (navigator.appName.toLowerCase().indexOf('explorer') > -1) {
func = new Function(functionPrefix + " " + ev);
}
else {
func = new Function("event", functionPrefix + " " + ev);
}
As a result, in the default case that there's no other onchange registered, this sets up the onchange for the input to be the equivalent of
function() { ValidatorOnChange(event); }
in IE and
function(event) { ValidatorOnChange(event); }
in other browsers. So iff you're using IE, the event passed to ValidatorOnChange will be window.event (since window is the global object).
A suggested solution
If you don't want to hack around with the ASP.Net scripts then I think the nicest way to handle this is to detect the broken event handler and replace it. As with other suggestions here, I offer an onSelect to include in the datepicker options.
onSelect: function(dateStr, datePicker) {
// http://stackoverflow.com/questions/1704398
if (datePicker.input[0].onchange.toString().match(/^[^(]+\(\)\s*{\s*ValidatorOnChange\(event\);\s*}\s*$/)) {
datePicker.input[0].onchange = ValidatorOnChange;
}
datePicker.input.trigger("change");
}
I'm applying this globally with
$.datepicker.setDefaults({
onSelect: function(dateStr, datePicker) {
etc.
}
});

It doesn't look like you're doing anything wrong since the ValidatorOnChange code is generated for you; there's something wrong in the way it's creating its vals object which appears to end up null on ie8.
It's been asked before, and the solution is overriding the onSelect function with a no-op function.
This is not the only kind of validator problem out there. Here's a vaguely similar issue with the autocomplete feature.

The fix...
onSelect: function() {}
..does not appear to work if the problem is with a CustomValidator that relies on a servewr side event handler to validate input.
There are a couple of other fixes mentioned here...
http://dev.jqueryui.com/ticket/4071
The problem is down to IE's event handling differing from other browsers and the client side validation code supplied by ASP Net not reacting gracefully to a situation not contemplated by it's authors.

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 (so it occurs after the default declarations and replaces the earlier version).
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();
}

change jquery.ui.datepicker.js line 1504
'" href="#" >' + printDate.getDate() + '</a>')
with
'" href="javascript:DP_jQuery_' + dpuuid + '.datepicker._selectDay(\'#' +
inst.id + '\',' + printDate.getMonth() + ',' + printDate.getFullYear() + ', this);" >' + printDate.getDate() + '</a>')
test works OK!

I don't really know what the problem is, but I did notice that your does not have the ValidationGroup set, and both of your validators have that value set. You might try setting ValidationGroup="sh" in your TextBox and see if that helps.

Building upon the above answers and to provide further detail to my comment above,
Apparently in IE9+ and other browsers, you should now use dispatchEvent to fire the change event. (Why does .fireEvent() not work in IE9?)
The OnSelect function in the datepicker actually has 2 arguments:
The value of the textbox associated with the datepicker
An object with an id property that matches that of the textbox
mytextbox.datepicker({
defaultDate: null,
numberOfMonths: 1,
dateFormat: DisplayDateFormat,
onSelect: function (value, source) {
}
});
All the examples I saw used document.getElementById() to retrieve the textbox, which I thought wouldn't be necessary seeing as the source object has the same id as the textbox. Upon closer examination it turns out that source is an object, not the textbox element. I found the following code resolved the problem though:
mytextbox.datepicker({
defaultDate: null,
numberOfMonths: 1,
dateFormat: DisplayDateFormat,
onSelect: function (value, source) {
var ctrl = document.getElementById(source.id);
if ("dispatchEvent" in ctrl) {
// IE9
var evt = document.createEvent("HTMLEvents");
evt.initEvent("change", false, true);
ctrl.dispatchEvent(evt);
} else if ("fireEvent" in ctrl) {
// IE7/IE8
ctrl.fireEvent("onchange");
} else {
$(ctrl).change();
}
}
});
Update: It appears that this approach is no longer working - not sure why. It stops the error from being thrown but doesn't trigger the change event.

Related

Why does my jquery-ui modal dialog disappear immediately after it opens?

I'm trying to use a simple jquery-ui modal dialog as a delete confirmation in an ASP.NET C# application. I've done this many times before, but for some reason in this application it is misbehaving. I see the dialog pop up then it immediately disappears before I can click on either "Yes" or "No". Here's the relevant code (Javascript):
<script type="text/javascript" src="/resources/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="/resources/jquery-ui-1.9.1.custom.min.js"></script>
<link rel="stylesheet" type="text/css" href="/resources/ui-lightness/jquery-ui-1.9.1.custom.css" />
<script type="text/javascript">
var remConfirmed = false;
function ConfirmRemoveDialog(obj, title, dialogText) {
if (!remConfirmed) {
//add the dialog div to the page
$('body').append(String.Format("<div id='confirmRemoveDialog' title='{0}'><p>{1}</p></div>", title, dialogText));
//create the dialog
$('#confirmRemoveDialog').dialog({
modal: true,
resizable: false,
draggable: false,
close: function(event, ui) {
$('body').find('#confirmRemoveDialog').remove();
},
buttons:
{
'Yes, remove it': function() {
$(this).dialog('close');
remConfirmed = true;
if (obj) obj.click();
},
'No, keep it': function() {
$(this).dialog('close');
}
}
});
}
return remConfirmed;
}
//String.Format function (since Javascript doesn't have one built-in
String.Format = function() {
var s = arguments[0];
for (var i = 0; i < arguments.length - 1; i++) {
var reg = new RegExp("\\{" + i + "\\}", "gm");
s = s.replace(reg, arguments[i + 1]);
}
return s;
}
</script>
Here's where I'm using the confirmation function (in the OnClientClick of an <asp:Button> control):
<asp:Button ID="btnRemoveProgram" runat="server" Text="Remove" CausesValidation="false" OnClientClick="ConfirmRemoveDialog(this, 'Please confirm removal', 'Are you sure you wish to remove the selected Program? This cannot be undone.');" />
As I said, I've successfully used this same construct (nearly identical code) many times before; I don't know why it isn't working now. Any ideas will be greatly appreciated, I'm truly stumped on this one.
The runat="server" is telling the button that it should post back to perform events at the server. The OnClientClick will be executed before that on the client side, so you will see the dialog and then immediate the page posts, causing the dialog to disappear.
The problem is that your modal dialog box is not modal in the traditional windows sense. The javascript continues on. The simplest test is to add an alert right before your return, you will see it pops up right after the dialog is shown.
To get around this issue, return false always in the OnContentClick and then in your Yes/No button event handlers use the __doPostback javascript method.
You need to return the remConfirmed to the caller which is the button itself. On your button, do this:
OnClientClick="return ConfirmRemoveDialog(/* the rest of the code */);"

Jquery help needed for onbeforeunload event

I am using jquery onbeforeunload event in asp.net application.
If i write event as given below then its working fine and display confirm dialog box.
var vGlobal = true;
var sMessage = "Leaving the page will lost in unsaved data!";
[ Working ]
> window.onbeforeunload = function() {
> if (vGlobal == false) return
> sMessage; }
but its not working if i use bind method like as given below
[ Not working ]
$(window).bind("beforeunload", function(e) {
if (vGlobal == false)
return sMessage;
});
Anybody suggest me why its not working.Is there any difference between these two methods.
Code on aspx:
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
CLICK ON THIS LINK TO SEE RUNNING EXAMPLE
See the updated version
You need to bind all the events inside document ready event.
Apart from the fact that vGlobal is true and you are checking if (vGlobal == false), this smells like a $(document).ready() issue.
I.e. you should place the declaration inside a document.ready() handler as shown here:
$(document).ready(function(){
$(window).bind("beforeunload", function(e) {
if (vGlobal == false)
return sMessage;
});
});
There is no benefit in using jQuery to bind the event to the window - all you are doing is adding the overhead of having jQuery parse the window into a jQuery object, which you aren't even using.
Therefore, using:
window.onbeforeunload = handler;
Is preferable to using jQuery to bind this event.
You can still perform the binding inside of the document ready section:
$(document).ready(function () {
window.onbeforeunload = handler;
};

ASP.NET, jQuery, dirty forms, and window.onbeforeunload

In my ASP.NET web app, I'm trying to create a universal way of warning users before navigating away from a form when they've made changes, using jQuery. Pretty standard stuff, but after a lot of searching I have yet to find a technique that works.
Here's what I have at this point:
addToPostBack = function(func) {
var old__doPostBack = __doPostBack;
if (typeof __doPostBack != 'function') {
__doPostBack = func;
} else {
__doPostBack = function() {
old__doPostBack();
func();
}
}
}
var isDirty = false;
$(document).ready(function() {
addToPostBack(function() {
alert("Postback detected.")
clearDirty();
});
$(':input').bind("change select keydown", setDirty);
window.onbeforeunload = function(e) {
var msg = "You have unsaved changes. "
if (isDirty == true) {
var e = e || window.event;
if (e) { e.returnValue = msg; }
return msg;
}
};
});
setDirty = function() {isDirty = true;}
clearDirty = function() {isDirty = false;}
This works as far as warning the user from navigating away. The problem is that I get the warning on every same-page postback. There are a number of things on my forms that might trigger a postback:
There are Save, Cancel, and Delete linkbuttons on the page
There might be other linkbuttons on the page that execute server-side functionality while staying on the same page
There might be other controls with autopostback=true that also have server-side functions attached to them, but which don't result in the user leaving the page.
None of these things should provoke a warning, because the user isn't leaving the page. My code tries to hijack addToPostBack (more details on that in this question) to clear the isDirty bit before posting back, but the problem is that in IE onbeforeunload fires before __doPostBack, apparently because IE fires onbeforeunload immediately when a link is clicked (as described here).
Of course, I could wire up each of these controls to clear the isDirty bit, but I'd prefer a solution that operates on the form level and that doesn't require that I touch every single control that might trigger a postback.
Does anyone have an approach that works in ASP.NET and that doesn't involve wiring up every control that might cause a postback?
I came across this post while Googling for a solution for doing the same thing in MVC. This solution, adapted from Herb's above, seems to work well. Since there's nothing MVC-specific about this, it should work just as well for PHP, Classic ASP, or any other kind of application that uses HTML and JQuery.
var isDirty = false;
$(document).ready(function () {
$(':input').bind("change select keydown", setDirty);
$('form').submit(clearDirty);
window.onbeforeunload = function (e) {
var msg = "You have unsaved changes. "
if (isDirty == true) {
var e = e || window.event;
if (e) { e.returnValue = msg; }
return msg;
}
};
});
setDirty = function () { isDirty = true; }
clearDirty = function () { isDirty = false; }
Interesting, but... why don't you do everything with jQuery?
var defaultSubmitControl = false;
var dirty = false;
$(document).ready(function( ) {
$('form').submit(function( ) { dirty = false });
$(window).unload(function( ) {
if ( dirty && confirm('Save?') ) {
__doPastBack(defaultSubmitControl || $('form :submit[id]').get(0).id, '');
}
});
});
···
dirty = true;
···
Now, if that still causes the same issue (unload triggering before submit), you could try a different event tree, so instead of calling __doPostBack directly you do...
setTimeout(function( ) {
__doPastBack(defaultSubmitControl || $('form :submit[id]').get(0).id, '');
}, 1); // I think using 0 (zero) works too
I haven't tried this and it's from the top of my head, but I think it could be a way to solve it.
You could always create an inherited page class that has a custom OnLoad / OnUnload method that adds in immediate execution JavaScript.
Then you don't have to handle it at a control specific level but rather the form / page level.
Got this to work by basically tracking the mouse position. Keep in mind you can still get positive values to your Y value (hence my < 50 line of code), but as long as your submit buttons are more than 100 pixels down you should be fine.
Here is the Javascript I added to track mouse changes and capture the onbeforeunload event:
<script language="JavaScript1.2">
<!--
// Detect if the browser is IE or not.
// If it is not IE, we assume that the browser is NS.
var IE = document.all?true:false
// If NS -- that is, !IE -- then set up for mouse capture
if (!IE) document.captureEvents(Event.MOUSEMOVE)
// Set-up to use getMouseXY function onMouseMove
document.onmousemove = getMouseXY;
// Temporary variables to hold mouse x-y pos.s
var tempX = 0
var tempY = 0
// Main function to retrieve mouse x-y pos.s
function getMouseXY(e) {
if (IE) { // grab the x-y pos.s if browser is IE
tempX = event.clientX + document.body.scrollLeft
tempY = event.clientY + document.body.scrollTop
} else { // grab the x-y pos.s if browser is NS
tempX = e.pageX
tempY = e.pageY
}
// catch possible negative values in NS4
if (tempX < 0){tempX = 0}
if (tempY < 0){tempY = 0}
// show the position values in the form named Show
// in the text fields named MouseX and MouseY
document.Show.MouseX.value = tempX
document.Show.MouseY.value = tempY
return true
}
//-->
</script>
<script type="text/javascript">
window.onbeforeunload = HandleOnClose;
function HandleOnClose(e) {
var posY = 0;
var elem = document.getElementsByName('MouseY');
if (elem[0]) {
posY = elem[0].value;
}
if (posY < 50) { // Your form "submit" buttons will hopefully be more than 100 pixels down due to movement
return "You have not selected an option, are you sure you want to close?";
}
}
</script>
Then just add the following form onto your page:
<form name="Show">
<input type="hidden" name="MouseX" value="0" size="4">
<input type="hidden" name="MouseY" value="0" style="display:block" size="0">
</form>
And that's it! It could use a little cleanup (remove the MouseX, etc), but this worked in my existing ASP.net 3.5 application and thought I would post to help anyone out. Works in IE 7 and Firefox 3.6, haven't tried Chrome yet.
i am looking after this too but what i have find so far is, a solution that uses all the html controls instead of asp.net web controls, have you think of that?
<script type="text/javascript">
$(document).ready(function () {
$("form").dirty_form();
$("#btnCancel").dirty_stopper();
});
</script>

ASP.NET: Scroll to control

I've got a particularly large form in an page. When the form is validated and a field is invalid, I want to scroll the window to that control. Calling the control's Focus() doesn't seem to do this. I've found a JavaScript workaround to scroll the window to the control, but is there anything built into ASP.NET?
Page.MaintainScrollPositionOnPostBack = False
Page.SetFocus(txtManagerName)
Are you using a Validation Summary on your page?
If so, ASP.NET renders some javascript to automatically scroll to the top of the page which may well override the automatic behaviour of the client side validation to focus the last invalid control.
Also, have you turned client side validation off?
If you take a look at the javascript generated by the client side validation you should see methods like this:
function ValidatorValidate(val, validationGroup, event) {
val.isvalid = true;
if ((typeof(val.enabled) == "undefined" || val.enabled != false) &&
IsValidationGroupMatch(val, validationGroup)) {
if (typeof(val.evaluationfunction) == "function") {
val.isvalid = val.evaluationfunction(val);
if (!val.isvalid && Page_InvalidControlToBeFocused == null &&
typeof(val.focusOnError) == "string" && val.focusOnError == "t") {
ValidatorSetFocus(val, event);
}
}
}
ValidatorUpdateDisplay(val);
}
Note the call to ValidatorSetFocus, which is a rather long method that attempts to set the focus to the control in question, or if you have multiple errors, to the last control that was validated, using (eventually) the following lines:
if (typeof(ctrl.focus) != "undefined" && ctrl.focus != null) {
ctrl.focus();
Page_InvalidControlToBeFocused = ctrl;
}
To get this behaviour to work, you would ideally need to ensure that all your validators are set to be client-side - server side validators will obviously require a postback, and that might affect things (i.e. lose focus/position) - and setting MaintainScrollPositionOnPostBack to true would probably cause the page to reload to the submit button, rather than the invalid form element.
Using the server side .Focus method will cause ASP.NET to render out some javascript "on the page load" (i.e. near the bottom of the page) but this could be being overriden by one of the other mechanisms dicussed above.
SO I believe the problem is because I was trying to focus on HtmlGenericControls instead of WebControls.
I just ended up doing a workaround based off of:
http://ryanfarley.com/blog/archive/2004/12/21/1325.aspx
http://www.codeproject.com/KB/aspnet/ViewControl.aspx
...in the interest of time.
public static void ScrollTo(this HtmlGenericControl control)
{
control.Page.RegisterClientScriptBlock("ScrollTo", string.Format(#"
<script type='text/javascript'>
$(document).ready(function() {{
var element = document.getElementById('{0}');
element.scrollIntoView();
element.focus();
}});
</script>
", control.ClientID));
}
Usage:
if (!this.PropertyForm.Validate())
{
this.PropertyForm.ErrorMessage.ScrollTo();
failed = true;
}
(Although it appears Page.RegisterClientScriptBlock() is deprecated for Page.ClientScript.RegisterClientScriptBlock()).
Adding MaintainScrollPositionOnPostback is the closest that ASP.NET has built in, but won't necessarily jump to the invalid field(s).
<%# Page MaintainScrollPositionOnPostback="true" %>
Very simple solution is to set the SetFocusOnError property of the RequiredFieldValidator (or whichever validator control you are using) to true
Are you sure Focus() won't do what you're describing? Under the hood, it is essentially doing the "JavaScript workaround" - it writes some JS to the page which calls focus() on the control with the matching ID:
Whichever control had Focus() called last before the page finishes processing writes this to the page:
<script type="text/javascript">
//<![CDATA[
WebForm_AutoFocus('txtFocus2');//]]>
</script>
Please insert these into your OnClick event
Page.MaintainScrollPositionOnPostBack = false;
Page.SetFocus("cliendID");
// or
Page.setFocus(control);
You should looks into jQuery and the ScrollTo plugin
http://demos.flesler.com/jquery/scrollTo/
I've achieved something similar using basic HTML fragments. You just leave an element with a known ID:
<span id="CONTROL-ID"></span>
And then either via script, on on the server side change the url:
window.location += "#CONTROL-ID";
In the first case the page won't reload, it will just scroll down to the control.
Paste the following Javascript:
function ScrollToFirstError() {
Page_ClientValidate();
if (Page_IsValid == false) {
var topMostValidator;
var lastOffsetTop;
for (var i = 0; i < Page_Validators.length; i++) {
var vld = Page_Validators[i];
if (vld.isvalid == false) {
if (PageOffset(vld) < lastOffsetTop || lastOffsetTop == undefined) {
topMostValidator = vld;
lastOffsetTop = vld.offsetTop;
}
}
}
topMostValidator.scrollIntoView();
}
return Page_IsValid;
}
function PageOffset(theElement) {
var selectedPosY = 0;
while (theElement != null) {
selectedPosY += theElement.offsetTop;
theElement = theElement.offsetParent;
}
return selectedPosY;
}
Then call ScrollToFirstError() in your OnClientClick of the button that is saving, make sure the button has CausesValidation=true as well.
There you have it.

Javascript checking if page is valid

On my submit button, what I'd like to do is OnClick show a "Please wait" panel and hide the button, UNLESS the validators say something's invalid - then I need the buttons still showing obviously. Otherwise I have a validation summary showing erros and no way to submit again.
Most articles I find about doing this want to use Page_ClientValidate() function to tell the page to validate itself, but this comes back undefined for me, as does Page_IsValid variable. Here is the function I'm trying to use - what am I missing?:
function PleaseWaitShow() {
try {
alert("PleaseWaitShow()");
var isPageValid = true;
// Do nothing if client validation is not active
if (typeof(Page_Validators) == "undefined") {
if (typeof(Page_ClientValidate) == 'function') {
isPageValid = Page_ClientValidate();
alert("Page_ClientValidate returned: " + isPageValid);
alert("Page_IsValid=" + Page_IsValid);
} else {
alert("Page_ClientValidate function undefined");
}
} else {
alert("Page_Validators undefined");
}
if(isPageValid) {
// Hide submit buttons
document.getElementById('pnlSubmitButton').style.visibility = 'hidden';
document.getElementById('pnlSubmitButton').style.display = 'none';
// Show please wait panel
document.getElementById('pnlPleaseWait').style.visibility = 'visible';
document.getElementById('pnlPleaseWait').style.display = 'block';
} else {
alert("page not valid - don't show please wait");
}
} catch(er) {
alert("ERROR in PleaseWaitShow(): " + er);
}
}
change this line "if (typeof(Page_Validators) == "undefined") " to
if (typeof(Page_Validators) != "undefined")
According to the section "The Client-Side API" on the page "ASP.NET Validation in depth":
Page_IsValid | Boolean variable | Indicates whether the page is currently valid. The validation scripts keep this up to date at all times.
Indeed, watching this variable in FireBug on a form with ASP.NET client side validation enabled, it does get updated as I fill in details of the form (incorrectly, or correctly).
Obviously, if you've disabled client script on your validators or the validation summary, then this variable won't be available to you.
Just check
if(Page_IsValid)
{
//Yourcode
}
This works if you have validators in the page, which excludes the validation summary.
Page_ClientValidate() is not any standard javascript function i know of
I believe I've found a "kind of" answer.
I still cannot identify why my page will not identify "Page_ClientValidate()" or "Page_IsValid" - this part is still unanswered.
However, I am using a number of PeterBlum validators on the page, and those do provide a "VAM_ValOnSubmit()" that returns true/false. So this may be the solution. I might just have to be sure all the validators are PeterBlum to catch them all.
Not the greatest solution, but better than I've gotten so far. I'm still open to answers on the "Page_IsValid" portion.
There's an ASP.Net forum thread on this topic: Button that prevents multiple clicks
Here's the solution (in code behind):
private void BuildClickOnceButton(WebControl ctl)
{
System.Text.StringBuilder sbValid = new System.Text.StringBuilder();
sbValid.Append("if (typeof(Page_ClientValidate) == 'function') { ");
sbValid.Append("if (Page_ClientValidate() == false) { return false; }} ");
sbValid.Append(ctl.ClientID + ".value = 'Please wait...';");
sbValid.Append(ctl.ClientID + ".disabled = true;");
//GetPostBackEventReference obtains a reference to a client-side script function that causes the server to post back to the page.
sbValid.Append(ClientScript.GetPostBackEventReference(ctl, ""));
sbValid.Append(";");
ctl.Attributes.Add("onclick", sbValid.ToString());
}

Resources