javascript - Adding buttons in acending order and removing buttons in decending order -
i'm developing simple web page school assignment , wondering possible create button add button, button beside remove button?
basically button called “add button” if click on it, button same size(can named appropriate no functions required). no matter how many times click it, more buttons added e.g. button1, button2, button3 etc. also, next “add button” button button called “remove button” removes buttons descendingly e.g. button3, button2, button1.
somehow not of buttons removed. how can fix this?
html:
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script> <button type="button" class="btn" id="add_button">add</button> <button type="button" class="btn" id="delete_button">delete</button> <div class="result"> </div> js:
var start = 0; $(document).on("click","#add_button",function(){ start++; $(".result").append($('<button id="add_button">add'+start+'</button>').addclass('button'+start)); }); $(document).on("click","#delete_button",function(){ start--; $(".result").find('#add_button').each(function(index, el) { $('.button'+start).remove(); });; }); fiddle:
you don't need add dynamic classes, switch id class add_button , use .eq(start) select button.add_button @ start index:
var start = 0; $(document).on("click", ".add_button", function(){ start++; $(".result").append($(this).clone().text('add'+start)); }); $(document).on("click","#delete_button",function(){ if ($('.add_button').length > 1) { $('.add_button').eq(start--).remove() } }); <script src="https://code.jquery.com/jquery-2.2.4.min.js"></script> <button type="button" class="btn add_button">add</button> <button type="button" class="btn" id="delete_button">delete</button> <div class="result"></div>
Comments
Post a Comment