简体   繁体   中英

Set focus to input before validator span

I am displaying an input field followed by a br tag and a span for a validation message. There are three of these for a login form. I want to locate the first field with a visible validation message (span has a class assigned) and set focus to the input associated with the span.

My html looks like thus:

<div id="loginForm">
    <label class="formLabel" for="Login_LastName">Your last name</label>
    <input id="Login_LastName" name="Login_LastName" type="text" maxlength="31" style="width:200px;" /><br />
    <span id="Login_LastName_validator"></span>

    . . .
</div>

I am trying to use the following javascript but it's not finding the input:

$("#loginPanel").find("validationMsg:first").prev("input").focus();

I can locate the validation span it appears as I can alert the contents:

alert($("#loginPanel").find(".validationMsg:first").html());

I just cannot seem to locate the input object to set focus.

I am setting the validationMsg via javascript:

if(!$.trim($("#Login_LastName").val())) {
    $("#Login_LastName_validator").html("Your last name is required<br /><br />")
        .addClass("validationMsg");
    loginFormValid = false;
}
else {
    $("#Login_LastName_validator").html("")
        .removeClass("validationMsg");
}

Found a solution. I think I had to get it past the break tag. Looks like prev() only checks the one element previous? It does not keep going?

$("#loginPanel").find(".validationMsg:first").prev().prev("input").focus();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM