How do I expect everything to load before running a function?

5

How can I delay a function, since the checkboxes are generated dynamically in the conventional way in javascript, and only run after the entire page has been rendered and the other javascripts have been executed?

I'm trying to use this code:

var count = 0;
$('input:checkbox').click(function(){
    if( $(this).is(':checked') ){
        count++;
    }else{
        count--;
    }
    $('#count').html( count );
});

And the one to display in the html:

<p><div id="count">0</div></p>
    
asked by anonymous 14.08.2015 / 04:05

2 answers

5

Because you are dynamically generating checkboxes, you need to bind the click event when they are created.

In your case, the easiest way to do this is to replace the following code string:

$('input:checkbox').click(function () { ... });

by the following:

$(document).on("click", "input:checkbox", function () { ... });

This way, whenever a input:checkbox is added to document the jQuery itself will bind the click event to this newly created element.

If all inputs belong to the same form, I recommend using $("form-id") rather than $(document) .

    
14.08.2015 / 14:34
0

try to use the done function after the click event:

var count;
$('input:checkbox').click(function(){
    if( $(this).is(':checked') ){
        count++;
    }else{
        count--;
    }       
}).done(function(){ 
    $('#count').html( count );
});
    
14.08.2015 / 14:34