3

I have a function that executes a number of times. I want to find using jQuery how many times the function is called. How do I do that?

Whenever a text field is changed, function showErrors is called. So depending on the number of text fields on a page, I should be able to find the number of times showErrors is called. how will I detect that within the showErrors function.

showErrors: function(errorMap, errorList) {  
    if ($formEl.find(".aimInput input").length == 2) {
        // $('.validate').html(errorList[0]['message']);
        $(".aimLocal .submit").removeClass("disabled");
        $(C.options.currentPage).find('input[type="submit"]').removeAttr("disabled");
    }
}
1
  • 3
    how does your code looks like ? Commented Aug 15, 2012 at 20:05

4 Answers 4

7
var i = 0;

$("div").each(function() {
    ...
    i++;
});

alert( i );
Sign up to request clarification or add additional context in comments.

6 Comments

How about $("div").length?? OP says its a function.. his post title and the post is not very clear.
@Vega good point, but the handler might being called multiple times on those divs, so there are 3 div-s but the function run 9 times, for example
@Vega, you can break out of an .each() loop by returning false, or continue by returning true, so .length may not always be accurate.
@DerekHunziker check out his edited post or probably ask OP to show his code to see if doing something like that.. in this answer, there is no return false :P
@Vega in this answer there is a ... that might be ANYTHING what the OP writes :)
|
5

jQuery handles this for you. Try this:

$("something").each(function(index) {
    alert("Current index is " + index);
});

Comments

4
var errors = 0;

(...)

showErrors: function(errorMap, errorList) {                                                                                                             

    if($formEl.find(".aimInput input").length == 2) {     
        // $('.validate').html(errorList[0]['message']);

        $(".aimLocal .submit").removeClass("disabled");                               
        $(C.options.currentPage).find('input[type="submit"]').removeAttr("disabled");

        errors++;  // <--------------- THIS

    }                    
}

Then after, you can use errors anywhere in your code, as it's global.

Comments

0

You can simply count the number of elements

$("#foo > div").length

1 Comment

I thought that too at first, but then I figured he probably was looking for a running total

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.