Home > Software design >  Multiple check of form before submit with jquery
Multiple check of form before submit with jquery

Time:07-04

Before submitting a form I check for Title (getElementById("title")) length and for number of attached files (("#filesTable_ tr.template-download").length). If not ok I prevent submit and show an error notification previously scrolled a page to an element with error, as in snippet below.

$(document).ready(function(){
    $('#form').submit(function(e) {
        if(document.getElementById("title").value.length < 2)
        {
            e.preventDefault();
            $('html, body').animate({
                scrollTop: $("input[name='rpagetitle']").offset().top-70
            }, 600);                                        
            //here I show an error notifications
        }
        if($("#filesTable_ tr.template-download").length < 1)
        {
            e.preventDefault();
            $('html, body').animate({
                scrollTop: $("#dropzone").offset().top-70
            }, 600);                                        
            //here I show an error notifications
        }
        {
            return true;
        }
    });
});

But if both checks fail the page is scrolling two times, first to the title and than to the dropzone, how can I prevent second check (("#filesTable_ tr.template-download").length < 1)) if a first check fails? So if Title is not OK, scroll to it, show error. If Title is OK, check Files, if not OK, scroll to it, show error. If both OK, submit form.

CodePudding user response:

Use return false; in your first condition block so that if the first case is false then it just runs only one block.

The return statement is used to return a particular value from the function to the function caller. The function will stop executing when the return statement is called. The return statement should be the last statement in a function because the code after the return statement will be unreachable.

  • Related