jQuery: hasClass/length

OK, this has to be something completely simple that I’m overlooking. I have a callback function for .getJSON, and it applies a certain class (“error”) if it finds an error when looping through the JSON output (an associative array). Everything works great, the class is applied, and I can see the resulting style changes. However, after the function I check to see if any elements in the document have the “error” class assigned to them, and none do. I tried:

$(‘.error’).length and also $(‘input’).hasClass(‘error’), and in both cases the result is 0 (zero)/false. Why doesn’t this work? And is there a better way I should be trying to do this? Thanks for any help!

Hard to say without seeing all the involved code.

Thanks for the reply. Here’s the only part of the code that’s relevant. The addClass(‘missing’) works fine, but the alert() results in 0 (zero). I thought maybe using the class selector doesn’t work since the class was added after the page was loaded, but hasClass(‘missing’) yielded no better results.

$.getJSON('/myurl.php', function(data) {
            for(var index in data)
            {
                    $('#' + index).addClass('missing');
            }
        });
        alert($('.missing').length);

Thanks.

The alert is outside the getJSON block, and since the JSON is fetched asynchronously, that means the alert is being executed before the JSON is processed.

OK, that makes sense. So… how might I determine outside of the getJSON block whether or not the “error” class was assigned to any elements during the execution of the getJSON block? What I’m really trying to do is make sure that the form doesn’t submit (using i.preventDefault). I already learned that I can’t set a global variable from within a function, and trying to assign a value to a hidden form input element didn’t work either (presumably for the same asynch reason. Thanks again.

The function that’s passed to getJSON doesn’t get executed right away. It gets run instead long after the rest of your code is done.

Anything that needs to rely on that function must be done inside of that function, or be called by it.

Thanks once again. I got it to work by changing the submit button type from “submit” to “button” (and the event handler from submit to click) and then forcing the submit within the getJSON block after it was determined that everything was OK with the form. I couldn’t think of any other way. I couldn’t use i.preventDefault within the getJSON block, and if I used it before the getJSON block, I wasn’t able to force the submit from within it. It seems once you’ve used i.preventDefault, there’s no undoing it (at least not that I was able to figure out).

Thanks!