2

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!

  • this would be easier if you turn the variable into an object, that's if the answers below doesn't solve the problem – Jay Harris Jul 14 '13 at 21:30

2 Answers2

0

Try:

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

Maybe try assigning countingdivs with the current length of #hold > div

var countingdivs = $("#hold > div").length;
Shawn31313
  • 5,978
  • 4
  • 38
  • 80
0

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) {
      // ...
    }
}
Ram
  • 143,282
  • 16
  • 168
  • 197
  • This is exactly what I needed and works perfectly! Thank you very much. I'm still new to all this but moving the condition to the handler makes much more sense. Thank you again!!! – user2581676 Jul 15 '13 at 01:21