Look at this:
$('form).submit(function (event) {
$(':input.required').trigger('blur');
var num = $('.warning', this).length;
alert(num);//Focus here!
if (num) {
event.preventDefault();
};
});
if there’re 5 required textbox is empty,then when click the submit button[ID:button1], the num is 5.After triggering the 5 textbox, finding 5 errors, and the code run well.
Also the same button[ID:button1]
$('#button1').click(function (event) {
$(':input.required').trigger('blur');
var num = $('.warning', this).length;
alert(num); //Focus here!
if (num) {
event.preventDefault();
};
});
In this example, the num is 0. Seem like the trigger function is not work well or in time.
Can someone tell me why?
thank you very much!
I believe it’s the reference to ‘this’. this is a special variable in JavaScript and many other languages. When you use it in the first example, it’s searching the form (this) for child elements with a class of “warning”. In the second example, it’s searching the button for child elements. You can just use
to find all elements on the page with that class. If you need to restrict the look up to just children of your form, try
Your first example, attaching to the form’s submit action, should be enough. Clicking the button will cause the submit event, so the second event handler is redundant (and wouldn’t fire if a user submitted the form by pressing enter in a field).