Skip to content Skip to sidebar Skip to footer

Why Is My Jquery Script For Checking Required Input Fields So Slow?

I am trying to use jQuery to check for required input fields for browsers that don't reccognise the required HTML tag. My jQuery script is as follow. $('div').on('submit', '#myform

Solution 1:

The delegated submit handler is not bound directly to the form element so you can't unbind the handler that way. You are creating an infinite loop. You should use the off method and unbind the handler of the div element.

Also note that the returned value of the each callback doesn't affect run flow of the wrapper, submit handler. Each function has it's own returned value.

$('div').on('submit', '#myform', function(e){     
    var $e = $('.error').empty();
    var $invalids = $(':input[required]').filter( function (e) { 
        var invalid = this.value.trim().length === 0;
        if ( invalid ) {
            $e.append('<p>' + this.name + " is required</p>");
        }
        return invalid;       
    }); 
    if ( $invalids.length ) {
       return false;
    }
    this.submit();
}); 

The submit method of HTMLFormElement object doesn't trigger jQuery submit handler so there is no need to unbind the handler. If the validation passes the form is submitted normally.

Performance-wise you can also avoid using :input selector. From jQuery :input documentation:

Because :input is a jQuery extension and not part of the CSS specification, queries using :input cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method. To achieve the best performance when using :input to select elements, first select the elements using a pure CSS selector, then use .filter(":input").

The elements property of the HTMLFormElement object returns a HTMLFormControlsCollection object in HTML5 browsers and a HTMLCollection object in HTML4 browsers that contains all the controls of the form element. You could also use this property instead of querying the DOM and use the jQuery filter method for filtering required fields:

 $(this.elements).filter('[required]');

Solution 2:

When you call submit() in last line you create infinite loop.


Post a Comment for "Why Is My Jquery Script For Checking Required Input Fields So Slow?"