Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I delete line breaks and text inputs dynamically with JavaScript?

I created a small website where I would like to add/remove input fields dynamically. I already wrote the code to add them and it works perfect but removing the input fields is a bit of a challenge.

Below is what my document looks like after creating the inputs. Now with the "remove button" I tried to remove the last BR and the 3 inputs fields above, but whatever I try I always remove the last 3 buttons, which is ok, and both brs above and beneath the three inputs.

var total_inputs = 9;
var place_br_before = false;

function remove_inputs() {
  if (total_inputs != 0) {
    place_br_before = true;
    
    for (var j = 0; j < 3; j++) {
      var del = document.getElementById(("input_" + total_inputs));
      del.remove();
      total_inputs--;
    }
    $('#inputs br:last-child').remove();
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<button type="button" onclick="add_inputs()">+</button>
<button type="button" onclick="remove_inputs()">-</button>

<form id="inputs">
  <input type="text" id="input_1">
  <input type="text" id="input_2">
  <input type="text" id="input_3">
  <br>
  <input type="text" id="input_4">
  <input type="text" id="input_5">
  <input type="text" id="input_6">
  <br>
  <input type="text" id="input_7">
  <input type="text" id="input_8">
  <input type="text" id="input_9">
  <br>
</form>
like image 697
Mister X CT Avatar asked Jul 17 '26 00:07

Mister X CT


1 Answers

I would probably simplify and abstract out the ID requirement by grouping rather than using line breaks.

function remove_inputs() {
  inputGroups = document.getElementsByClassName('input-group');
  inputGroups[inputGroups.length - 1].remove();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<button type="button" onclick="add_inputs()" disabled>+</button>
<button type="button" onclick="remove_inputs()">-</button>

<form id="inputs">
  <div class="input-group">
    <input type="text">
    <input type="text">
    <input type="text">
  </div>
  <div class="input-group">
    <input type="text">
    <input type="text">
    <input type="text">
  </div>
  <div class="input-group">
    <input type="text">
    <input type="text">
    <input type="text">
  </div>
</form>
like image 75
isherwood Avatar answered Jul 19 '26 15:07

isherwood



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!