How to expect everything to load before performing a function?

Asked

Viewed 1,301 times

5

How can I delay a function, being that checkboxs are generated dynamically, in the conventional way in javascript, and only run after the whole page is rendered and the other Avascripts are executed?

I’m trying to use that code:

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

And this to show in html:

<p><div id="count">0</div></p>

2 answers

5


as you are generating the checkbox dynamically, 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 () { ... });

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

if all inputs belong to the same form, I advise using $("form-id") instead of $(document).

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 );
});
  • Unfortunately your help has returned this. Uncaught TypeError: $(...).click(...).done is not a function. Thank you for trying to help!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.