How to focus first input?

前端 未结 3 793
日久生厌
日久生厌 2021-01-29 05:49

I have a ASP.NET MVC application and I want to focus the first field in error. On submit, if the last field has error and user tries to submit the form, the focus is going to th

相关标签:
3条回答
  • 2021-01-29 06:24

    @Palash has a good answer but I will explain why your code does not work so you understand it.

    You need to leave the loop after the focus is set to the first item by returning false like below:

    $(".input-validation-error").each(function () {
        $(this).focus();
        return false;
    });
    

    When you return false, you are instructing jQuery to stop processing the rest of the elements.Otherwise, it will keep looping and you will end up focusing the last item.

    0 讨论(0)
  • 2021-01-29 06:40

    You can use eq method.

    eq method reduces the set of matched elements to the one at the specified index.

    $('.input-validation-error').eq(0).focus();
    
    0 讨论(0)
  • 2021-01-29 06:42

    No need to use each here and loop over all errors. You can just set the focus to first element with error class input-validation-error like:

    $('.input-validation-error:first').focus();
    
    0 讨论(0)
提交回复
热议问题