0

我有一些带有 CustomValidators 的控件,如下所示。但是 SetFocusOnError 不起作用,如果验证失败,页面不会跳转到第一个控件。我可以在 javascript 中设置焦点,但问题是总是最后一个无效的控件获得焦点,这不是我想要的,我希望第一个无效的控件获得焦点。

谁能告诉我如何解决这个问题?谢谢。

function ValidateRootCause(source, args) {
    var status = document.getElementById("<%=statusDropDownList.ClientID %>");
    var RootCause = document.getElementById("<%=txtRootCause.ClientID %>");

    args.IsValid = true;
    if (RootCause.value == "" && (status.value == 21 || status.value == 18)) {
        args.IsValid = false;
        RootCause.focus();
    }
}

        <tr>
            <td width="45%">Root Cause (Why it Happens)<span class="littlefont">*</span>                
            <asp:CustomValidator ID="cvRootCause" runat="server" 
                    ErrorMessage="Required Field!" CssClass="warning" 
                    ClientValidationFunction="ValidateRootCause" ValidationGroup="formValidation" SetFocusOnError="True">
            </asp:CustomValidator>
            </td>
            <td width="55%">

                <asp:TextBox ID="txtRootCause" runat="server" TextMode="MultiLine" 
                    MaxLength="1000"></asp:TextBox>
            </td>
        </tr>
4

1 回答 1

1

创建一个名为“focusGiven”或类似名称的全局(在您的函数之外)JavaScript 变量。在你的 if() 中,围绕你的焦点调用包装另一个 if() 检查。这样它只会发生一次。

var focusGiven = false;
function ValidateRootCause(source, args) {
    var status = document.getElementById("<%=statusDropDownList.ClientID %>");
    var RootCause = document.getElementById("<%=txtRootCause.ClientID %>");

    args.IsValid = true;
    if (RootCause.value == "" && (status.value == 21 || status.value == 18)) {
        args.IsValid = false;

        if (!focusGiven) {
            RootCause.focus();
            focusGiven = true;
        }
    }
}
于 2011-12-08T17:51:56.623 回答