Automated numbers?

I am trying to add more fields. So when I click the button add more, it should add a number 1. textfield and a dropdown menu. and if you click again, he must do 2. textfield and a dropdown menu.

I created this code to create a new field, but the counter will not match if I delete the record in the middle

$(document).ready(function() {
  var max_fields = 10; //maximum input boxes allowed
  var wrapper = $(".input_fields_wrap"); //Fields wrapper
  var add_button = $(".add_field_button"); //Add button ID

  var x = 1; //initlal text box count
  $(add_button).click(function(e) { //on add input button click
    e.preventDefault();
    if (x < max_fields) { //max input box allowed
      x++; //text box increment
      $(wrapper).append('<div><input type="text" name="mytext[]"/><a href="#" class="remove_field">Ta  bort</a></div>'); //add input box
    }
  });

  $(wrapper).on("click", ".remove_field", function(e) { //user click on remove text
    e.preventDefault();
    $(this).parent('div').remove();
    x--;
  })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="input_fields_wrap">
  <button class="add_field_button">Lägg till fler svar</button>
  <div>
    <input type="text" name="mytext[]">
  </div>
</div>
Run codeHide result
+4
source share
1 answer

If it's just for showing purpose, use a CSS counter:

$(document).ready(function() {
  var max_fields = 10; //maximum input boxes allowed
  var wrapper = $(".input_fields_wrap"); //Fields wrapper
  var add_button = $(".add_field_button"); //Add button ID

  var x = 1; //initlal text box count
  $(add_button).click(function(e) { //on add input button click
    e.preventDefault();
    if (x <= max_fields) { //max input box allowed
      x++;
      $(wrapper).append('<div class="count"><input type="text" name="mytext[]"/><select><option value="1">1</option><option value="2">2</option><option value="3">3</option></select><a href="#" class="remove_field">Ta  bort</a></div>'); //add input box
    }
  });

  $(wrapper).on("click", ".remove_field", function(e) { //user click on remove text
    e.preventDefault();
    $(this).parent('div').remove();
    x--;
  })
});
.input_fields_wrap {
  counter-reset: count;
}
.count:before {
  counter-increment: count;
  content: counter(count) ".";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="input_fields_wrap">
  <button class="add_field_button">Lägg till fler svar</button>
  <div>
    <input type="text" name="mytext[]">
  </div>
</div>
Run codeHide result
+4
source

Source: https://habr.com/ru/post/1618284/


All Articles