Search code examples
javascriptjqueryvariablesvarupdating

How to update variable in javascript/jquery after click?


I am trying to write some code that only allows buttons with the .add class function on click if there are fewer than 3 immediate children divs within the #hold placeholder div. theDiv_append is a seperate function that adds a div block within #hold div placeholder. I am trying to update the countingdivs variable to then count and update the number of divs within #hold, but it's not working. Currently, the add button does not get disabled.

   var countingdivs = '1'; 
    if(countingdivs <= '2') {
  $(document).on('click',".add",theDiv_append);
    countingdivs = $("#hold > div").length;
   };

Any help would be great. Thanks!


Solution

  • Move the condition to the click handler:

    $(document).on('click', '.add', theDiv_append);
    
    function theDiv_append() {
        var $hold = $('#hold'),
            len = $hold.children('div').length;
    
        if (len <= 2) {
          // ...
        }
    }