1

How can i change this code to do it with limit max 25 times. User can delete block and add it again, always with a max of 25 times

HTML

holderBlock - it holds everithing

repeaterIngredient - this is the cloned div

<div id="holderBlock">

<div class="repeaterIngredient">                         

    <div class="row grid-12-12">
        <label for="extens_ingredientName" title="Tooltip Information">Ingredient name<span class="entity">T4094</span><em class="form-req"><img src="../../Content/Images/ico_transparent.png" alt="required" /></em></label>
        <textarea name="extens_ingredientName" id="extens_ingredientName" class="textArea70"></textarea>
    </div>

    <div>
        <input type="button" value="Remove Ingredient" title="Remove Ingredient" class="formee-button right remove_ingredient">
        <input type="button" value="Add New Ingredient" title="Add New Ingredient" class="formee-button right add_ingredient">
    </div> 

</div>

Jquery

This code is for clone the repeaterIngredient class and increment the for, name and id of all form elements inside The user can create another repeaterIngredient and delete it, but i need to change this code so than it stops wen it hits 25 divs and to work again if user delete div and add it again

var template = $('#holderBlock .repeaterIngredient:first').clone(),

        ingredientsCount = 1;

        var addIngredient = function () {

            ingredientsCount++;

            var repeaterIngredient = template.clone().find(':input').each(function () {

                var newId = this.id.substring(0, this.id.length - 1) + ingredientsCount;

                $(this).prev().attr('for', newId); // update label for (assume prev sib is label)

                this.name = this.id = newId; // update id and name (assume the same)

            }).end() // back to .repeaterIngredient

                .attr('id', 'repeaterIngredient' + ingredientsCount) // update repeaterIngredient id

                .appendTo('#holderBlock'); // add to container
        };

        //EXECUTE FUNCTION
        $('input.add_ingredient').live("click", addIngredient); // attach event

        // HIDE FIRST REMOVE BUTTON
        $('#holderBlock input.remove_ingredient:first').hide();

        // DELETE CREATED BLOCK
        $('input.remove_ingredient').live("click", function () {
            //console.log($(this).parent());
            $(this).parent().parent().hide();
            return false;
        });
4

1 に答える 1

1

作成する前に、表示される div をカウントする必要があります。

if ($('.repeaterIngredient:visible').count() > 25)
  return;

また、クラスを追加する必要がありますrepeaterIngredient

...
.attr('id', 'repeaterIngredient' + ingredientsCount)
.addClass('repeaterIngredient')
.appendTo('#holderBlock');
...

.repeaterIngredient非表示にする代わりに削除すると、スクリプトの最適化を容易にすることができます。

$(this).parent().parent().remove();

目に見えるアイテムを数える必要はありません:

if ($('.repeaterIngredient').count() > 25)
  return;

PS私はこのコードをテストしません。お役に立てれば幸いです。

于 2012-08-16T12:30:31.953 に答える