ASP.NET: Custom SetFocusOnError behavior for RequiredValidators
Is there a way I can override the default scrolling using when SetFocusOnError = true? Right now it pops the user up the page so that the top of the control is at (0,0). The problem is that our labels are above the controls, so the user can't see the label without scrolling up a little more. I'd like to make it center the control vertically instead, and ideally even do a nice smooth jQuery slide up.
I tried like this but it didn开发者_如何学Python't work (never gets fired):
function WebForm_AutoFocus(obj) {
elem = document.getElementById(obj).scrollTop() - 200; //Go to 200px above where the element is
$('html, body').animate({ scrollTop: elem }, 350)
}
There might be a better way but one way is to customize ValidatorSetFocus method that is called to set focus upon valiation fail like below:
$(function () {
// on first time page load
if (typeof (Page_ClientValidate) != "undefined") {
ValidatorSetFocus = CustomSetFocus;
}
}
function CustomSetFocus(val, event) {
var ctrl;
if (typeof (val.controlhookup) == "string") {
var eventCtrl;
if ((typeof (event) != "undefined") && (event != null)) {
if ((typeof (event.srcElement) != "undefined") && (event.srcElement != null)) {
eventCtrl = event.srcElement;
}
else {
eventCtrl = event.target;
}
}
if ((typeof (eventCtrl) != "undefined") && (eventCtrl != null) &&
(typeof (eventCtrl.id) == "string") &&
(eventCtrl.id == val.controlhookup)) {
ctrl = eventCtrl;
}
}
if ((typeof (ctrl) == "undefined") || (ctrl == null)) {
ctrl = document.getElementById(val.controltovalidate);
}
if ((typeof (ctrl) != "undefined") && (ctrl != null) &&
(ctrl.tagName.toLowerCase() != "table" || (typeof (event) == "undefined") || (event == null)) &&
((ctrl.tagName.toLowerCase() != "input") || (ctrl.type.toLowerCase() != "hidden")) &&
(typeof (ctrl.disabled) == "undefined" || ctrl.disabled == null || ctrl.disabled == false) &&
(typeof (ctrl.visible) == "undefined" || ctrl.visible == null || ctrl.visible != false) &&
(IsInVisibleContainer(ctrl))) {
if ((ctrl.tagName.toLowerCase() == "table" && (typeof (__nonMSDOMBrowser) == "undefined" || __nonMSDOMBrowser)) ||
(ctrl.tagName.toLowerCase() == "span")) {
var inputElements = ctrl.getElementsByTagName("input");
var lastInputElement = inputElements[inputElements.length - 1];
if (lastInputElement != null) {
ctrl = lastInputElement;
}
}
if (typeof (ctrl.focus) != "undefined" && ctrl.focus != null) {
ctrl.focus();
Page_InvalidControlToBeFocused = ctrl;
var span = $($("#" + ctrl.id)[0]).prevAll('span');
elem = $(span[0]).offset().top; //Go to 200px above where the element is
$('html, body').animate({ scrollTop: elem }, 350);
}
}
}
Isn't thoroughly tested so check if that works for you.
精彩评论