javascript - jQuery: Count number of child elements inside a div, update number when element added/removed -
i'm adding child elements inside div using append() , counting/adding number each 1 using ++ +1 each time item added.
i want value automatically adjust if item removed, example if have 4 elements:
- element #1
- element #2
- element #3
- element #4
currently if element #3 removed list looks this:
- element #1
- element #2
- element #4
but want this:
- element #1
- element #2
- element #3
appreciate advice on should use achieve this, thanks.
example code: https://jsfiddle.net/wepsrzkm/
var price_rule_html = '<button class="remove_price_rule button" type="button">remove element</button>'; var price_rule_count = 1; var price_rule_count = jquery(".price_rule_area_1").children().length; jquery('.add_price_rule').click(function () { price_rule_count++; jquery('.price_rule_area_1').append('<div class="price_rule_wrapper"><div class="price_rule_count">element #<span>' + price_rule_count + '</span></div>' + price_rule_html + '</div>'); jquery(".remove_price_rule").click(function() { jquery(this).parents('.price_rule_wrapper').remove(); }); });
decrease
price_rule_count
1 when removing.after remove 1 element, alter existing elements
#number
. updated: arun p johny's answer, don't need traverse left elements, need change after removed one's text.the origin code register multiple events
.remove_price_rule
each time add item, means if create element 3 times, when remove one, logic in remove handler execute 3 times,price_rule_count
inconsistent actual counts if useprice_rule_count--
, however, if usejquery(".price_rule_area_1").children().length;
real count, stll redundant execute same logic many times. it's better use .on's delegate form here.
var price_rule_html = '<button class="remove_price_rule button" type="button">remove element</button>'; var price_rule_count = jquery(".price_rule_area_1").children().length; jquery('.add_price_rule').click(function () { price_rule_count++; jquery('.price_rule_area_1').append('<div class="price_rule_wrapper"><div class="price_rule_count">element #<span>' + price_rule_count + '</span></div>' + price_rule_html + '</div>'); }); +jquery('.price_rule_area_1').on("click", ".remove_price_rule", function() { // arun p johny's answer, need change text after removed element. $element = jquery(this).parents('.price_rule_wrapper'); $element .nextall('.price_rule_wrapper') .find('span') .text(function(index, prevtext) { return parseint(prevtext, 10) - 1; }); jquery(this).parents('.price_rule_wrapper').remove(); --price_rule_count; // slower elements don't need traversed. // jquery('.price_rule_wrapper').each(function(idx) { // $(this).find(".price_rule_count > span").text(idx + 1); // }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="price_rule_area_1"></div> <button class="button-primary add_price_rule" type="button">add element</button>
Comments
Post a Comment