In my form, I’ve added a class named required to all elements that cannot be empty. Then I’m looping through each element using $.each() and adding a class named border which will apply a 2px red border to all those elements.
var req = $('.required');
$.each(req, function(){
var curr_val = $(this).val();
if(! curr_val)
{
$(this).addClass('border');
}
});
Now there is vertical scrolling on the page and so when submit is clicked I want the page to scroll up to the first empty element so that the user will know something is wrong and that is the reason the form did not submit
WHAT I TRIED
I added this block in my earlier version of code
$.each(req, function(){
var curr_val = $(this).val();
if(! curr_val)
{
$(this).addClass('border');
$('html, body').animate({ // added for scrolling purposes
scrollTop: $(this).offset().top
}, 200);
}
});
This works, but the problem is that it will keep scrolling at every 0.2 sec interval till it reaches the last empty element. This looks very funny and undesirable to the user.
So I was wondering if there is way to make it to scroll to the first empty element is occurs and stop there even if there are more empty elements below it. When that is filled and submit is clicked again, scroll to the first empty element again and stop it right there.
JS Fiddle
Here is a JS Fiddle to get you started and to also give an idea about the funny behavior that I’m referring to. Notice how it keeps scrolling till it reaches the last element.
You run the animation for each element, the solution is as simple as adding a condition to do only the first time:
Here is your fiddle updated.