rpsep2
rpsep2

Reputation: 3111

form validation - focus on 'error' input

I'm showing error messages/ alerts for a registration form, which point to the input with the error.

I want to focus on this error input, too.

However, my code currently focuses on the last input?

heres a link. to recreate, simply click register without filling anything in. the error displays for the first div... but focuses on the last.

link

my code currently:

$('#register-btn').on('click', checkEmpty);

function checkEmpty(){
    var emptyDiv = $('.add-listing-input').filter(function() { 
        return $(this).val() == "";
    });

    if(emptyDiv.length > 0){
        var theTop = emptyDiv.position();
        var theBottom = theTop.top + emptyDiv.height() +25;
        var theText = emptyDiv.attr('id');
        $('#register-errors').css('top',theBottom+'px').show();
        $('#error-text').text('Your '+theText+' is missing, please fill in');
        emptyDiv.focus();
        emptyDiv.on('keydown', function(){
                $('#register-errors').hide();
                $('#error-text').text('');

        });
    }else{
        $('#register-errors').hide();
        $('#error-text').text('');
        checkEmails()
    }

}

Upvotes: 0

Views: 788

Answers (1)

Chris Barr
Chris Barr

Reputation: 34012

Since emptyDiv is actually a collection of all empty fields, saying something like emptyDiv.focus() will try to focus on all of them (which isn't possible) and apparently just focuses the last one instead.

Try using the .first() method to filter it down to exactly what you want: emptyDiv.first().focus()

Here's my suggested re-write:

//Select some elements once
var $registerErrors = $('#register-errors');
var $errorsMsg = $('#error-text');

//click the registed button
$('#register-btn').click(function(){
    var $emptyInputs = $('.add-listing-input').filter(function() { 
        return this.value == "";
    });

    if($emptyInputs){
        var $firstEmptyInput = $emptyInputs.first();

        var bottomPosition = $firstEmptyInput.position().top + $firstEmptyInput.height() +25;
        var inputId = $firstEmptyInput.attr('id');

        $registerErrors
            .css('top', bottomPosition)
            .show();

        $errorsMsg.text('Your '+ inputId +' is missing, please fill in');

        $firstEmptyInput
            .focus()
            .one('keydown', clearError); //this event only fires once!
    }else{
        clearError();
        checkEmails();
    }
});

function clearError(){
    $registerErrors.hide();
    $errorsMsg.text('');
}

Upvotes: 2

Related Questions