简体   繁体   中英

Numeration of dynamically created elements in jquery

I'm trying to create elements (in this case selectors) via a button while also beeing able to delete them via another button:

$(document).ready(function() {
    var max_fields      = 10;
    var wrapper         = $(".container1");
    var add_button      = $(".add_form_field");

    var x = 1;
    $(add_button).click(function(e){
      e.preventDefault();
      if(x < max_fields){
         x++;
        $(wrapper).append('<div> <fieldset class= "field1"> <select class= "selector1" name="selector*[add numeration here]*"> </select> </fieldset>  <a href="#" class="delete">Delete</a>   </div>'); //add selector box
      }
      else
      {
        alert('You Reached the limits')
      }
      });
      $(wrapper).on("click",".delete", function(e){e.preventDefault(); $(this).parent('div').remove(); x--
        ;})
});

I have no idea, how I can dynamically numerate the selector names from 1 to 10 via the var x. Any help would be much appreciated!

You can do it like name="selector' + x + '" , but the question is what should happen with the count if i delete 1.?

Notes:

if (x < max_fields) { currently only allows you to make 9, so if you want to make 10 use if (x <= max_fields) {

I've also moved x++ to the end of the if statement so it does not increase the number until the end.

Demo

 $(document).ready(function() { var max_fields = 10; var wrapper = $(".container1"); var add_button = $(".add_form_field"); var x = 1; $(add_button).click(function(e) { e.preventDefault(); var s = FindNext(); if (s > 0) { $(wrapper).append('<div> <fieldset class= "field1"> <select class= "selector1" name="selector' + s + '"> </select> </fieldset> <a href="#" class="delete">Delete</a> </div>'); x++; } else { alert('You Reached the limits') } }); $(wrapper).on("click", ".delete", function(e) { e.preventDefault(); $(this).parent('div').remove(); x--; }) function FindNext() { for (var i = 1; i < max_fields; i++) { if ($('select[name="selector' + i + '"]').length == 0) { return i; } } return 0; } });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button class="add_form_field">add</button> <div class="container1"></div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM