Question

I am trying to get size of a list inside of an each because there are multiple lists and each are being added to dynamically. It doesn't seem to be returning the right number, not sure why.

the count should return number of list items per section

also have a fiddle set up here: http://jsfiddle.net/Dqf8B/

  <section id="questionOne">
                <span class="surveyQuestion"></span>
                <form>
                    <input>
                    <a class="button">Add</a>
                </form>
                <p class="helperText">drag to prioritize</p>
                <ol class="draggable answers">
                </ol>
            </section>

            <section id="questionTwo">
                <span class="surveyQuestion"></span>
                <form>
                    <input>
                    <a class="button">Add</a>
                </form>
                <p class="helperText">drag to prioritize</p>
                <ol class="draggable answers">
                </ol>
            </section>

function checkIfHelperIsNeeded(counter) {
    if(counter == 2){
        helperText.slideToggle(function(){
            $(this).fadeIn();
        })
    if (counter < 2) { helperText.hide(); };
    }
}

$('.button').each(function(){
    var counter = $(this).parent("form").parent("section").find("ol").size();
    console.log(counter);
    $(this).click( function(){
        if(counter <= 5) {
            checkIfHelperIsNeeded(counter);
            var myCurrentInputTags = $(this).parent('form').children('input').val();
            var li = $('<li class="tag">'+myCurrentInputTags+'</li>');
            $('<span class="close"></span>').on('click', removeParent).prependTo(li);
            $(this).parent('form').parent('section').children('.draggable').prepend(li);
        } else { alert("only 5 answers per question allowed")}
    });
})

function removeParent() { 
    $(this).parent().fadeOut( function() {
        $(this).remove();
    }); 
}

var helperText = $(".helperText");
helperText.hide();
Was it helpful?

Solution

Currently it appears you are running the each() function only a single time when this script first loads. As such, you should not expect it to pick up any changes that are made dynamically to the DOM.

You then set up an onclick function to compare the counter value (which would always be the last calculated value for the last button), against what may be a different button. So in essence after the each() is run counter has a static value to which all buttons will be compared during click(). I am guessing this is not what you intended.

You should probably just calculate the size of the ol selection in the click() function as you are really gaining nothing from using this counter variable.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top