Fredrik
Fredrik

Reputation: 191

Automated numbers?

I'm trying to make a add more field. So when I press add more button it should add a number 1. textfield and a dropdown menu. and if you press once more it should do 2. textfield and a dropdown menu.

I have created this code to make a new field but the counter will not match if I delete an entry 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>

Upvotes: 4

Views: 103

Answers (1)

A. Wolff
A. Wolff

Reputation: 74420

If it is just for displaying purpose, use 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>

Upvotes: 4

Related Questions