views:

47

answers:

3

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!

+2  A: 

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

var num = $('.warning').length;

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

var num = $('form#myformid').find('.warning').length;

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).

Tom
Oh,I get it! I didn't learn well.Thank you.
Michael
+1  A: 

In your 2 example, the context of this is different:

 var num = $('.warning', this).length;

There are no warning elements inside the button, so the count is 0 in the second example.

It's better to use this in both places for a direct comparison:

var num = $('form .warning').length;
Nick Craver
Thank you too.Good luck
Michael
A: 

In your second piece of code, you are calling the

$(':input.required').trigger('blur');

on your button (#button1). You should reference your form instead, because now it's looking for inputs inside of that button.

soren.qvist