问题
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', function(e){
e.stopPropagation();
e.preventDefault();
$( ':input[required]').each( function (e) {
if ( this.value.trim() == '' ) {
$('.error').html(this.name + " is required");
return false;
}
});
$(this).unbind().submit();
});
But it is very slow to load! after I click the submit button for the form, it takes about 5 seconds before the error messahe shows! It seems it is taking some loops. Why is it that? How can I solve this?
回答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 DOMquerySelectorAll()
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]');
回答2:
When you call submit()
in last line you create infinite loop.
来源:https://stackoverflow.com/questions/29313838/why-is-my-jquery-script-for-checking-required-input-fields-so-slow