Marcin Nabiałek
Marcin Nabiałek

Reputation: 111839

Scroll to first error in jQuery without a warning in JavaScript console

I would like to scroll to the first error in my Bootstrap form using jQuery.

I used:

$('html, body').animate({
    scrollTop: ($('.has-error').first().offset().top)
},500);

and it's working fine but there is one small issue. In JavaScript console I get:

TypeError: $(...).first(...).offset(...) is undefined

if no elements with class has-error has been found (there are no errors). Of course if there is at least one element with this class, I get no warning.

I would like to remove this warning adding extra condition to check if first() returns object (it seems it always does but I would expect it to be empty if no element is found).

I tried to do the following:

var el = $('.has-error').first();
if (! $.isEmptyObject(el)) {
    $('html, body').animate({
            scrollTop: (el.offset().top)
    },500);
}

but it doesn't change anything. In JavaScript console there is still warning.

Is there any way to remove this warning? Or maybe using first() method cause that it's not possible to catch when no element with this class exist?

Upvotes: 0

Views: 2420

Answers (2)

Flipke
Flipke

Reputation: 971

If there are no errors, you should check whether .has-error exists, not only the first.

var el = $('.has-error');
if (el.length) {
    $('html, body').animate({
            scrollTop: (el.first().offset().top)
    },500);
}

Upvotes: 3

Jerodev
Jerodev

Reputation: 33196

You can count the elements to check if there are any errors.

if ($(".has-error").length) {
    $('html, body').animate({
            scrollTop: ($(".has-error").first().offset().top)
    },500);
}

The length function will return the number of elements found. In javascript, every number above 0 will be seen as true.

Upvotes: 1

Related Questions