Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count dynamically created divs

I'm trying to write a form builder where users can generate a signup form. I need to limit the amount of items that the user can create however they also need to delete the items.

Originally I had

var limit = 5;
var counter = 0;

if (counter == limit)  {

However when the user deleted items the counter remained the same and so they couldnt replace the deleted form element with a new item. So what I want to do is count how many items are currently active. I tried to do this by giving each new element a class (.kid) and then counting the amount of divs with that class but it didnt work.

Could anyone point me in the right direction? This is what I have so far however it doesn't work.

var limit = 6;
var num = $('.kid').length;

   function addAllInputs(divName, inputType){

    if (num == limit)  {
        alert("You have all ready added 6 form items");
    }
    else { 
    var newdiv = document.createElement('div');
        newdiv.setAttribute('id', 'child' + (counter + 1));
        newdiv.setAttribute('class', 'kid' );

Cheers all!

like image 593
Chris Avatar asked Jan 29 '26 13:01

Chris


1 Answers

You need to capture the current counter in a closure. Decrease the counter when the user deletes an item and increase it after an item is created. Your code sample doesn't reveal how you handle the deletion, but I'll try to illustrate what I mean with a small code snippet:

$(document).ready(function () {
    var limit = 5;
    var counter = $('.kid').length;

    $('#triggers_delete').click(function () {
        /* delete the item */
        counter--;
    });

    $('#triggers_creation').click(function () {
        if (counter == limit) {
            alert('Limit reached');
            return false;
        }
        /* somehow determine divName and inputType
           and create the element */    
        addAllInputs(divName, inputType);
        counter++;
    });
});

function addAllInputs(divName, inputType) {
    /* just create the item here */
}
like image 179
emboss Avatar answered Feb 01 '26 02:02

emboss



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!