remove all field from dynamic add field

Viewed 38

I'm working on the following jsfiddle code:

$(function() {
  $("#btnAdd").bind("click", function() {
    var div = $("<div />");
    div.html(GetDynamicTextBox(""));
    $("#TextBoxContainer").append(div);
  });
  $("#btnGet").bind("click", function() {
    var valuesarr = new Array();
    var phonearr = new Array();
    $("input[name=DynamicTextBox]").each(function() {
      valuesarr.push($(this).val());
    });
    $("input[name=phoneNum]").each(function() {
      phonearr.push($(this).val());
    });
    alert(valuesarr);
    alert(phonearr);
  });
  $("body").on("click", ".remove", function() {
    $(this).closest("div").remove();
  });
});

function GetDynamicTextBox(value) {
  return '<input name = "DynamicTextBox" type="text" value = "' + value + '" />&nbsp;<input name = "phoneNum" type="text" />&nbsp;<input type="button" value="Remove" class="remove" />';
}

example

It works perfectly but: I add more then one input field, for example 3 new rows (via add button), then I can remove each line with the "remove button". I would like to "remove all" rows... is it possible with a new button called "remove all" or something similar?

thanks for your help

1 Answers

$(function() {
  $("#btnAdd").bind("click", function() {
    var div = $("<div />");
    div.html(GetDynamicTextBox(""));
    $("#TextBoxContainer").append(div);
  });
  $("#btnGet").bind("click", function() {
    var valuesarr = new Array();
    var phonearr = new Array();
    $("input[name=DynamicTextBox]").each(function() {
      valuesarr.push($(this).val());
    });
    $("input[name=phoneNum]").each(function() {
      phonearr.push($(this).val());
    });
    alert(valuesarr);
    alert(phonearr);
  });
  $("body").on("click", ".remove", function() {
    $(this).closest("div").remove();
  });
  
  // remove all input field(s).
  $("#btnRemoveAll").bind("click", function() {
    $("#TextBoxContainer").empty();
  });
  
});

function GetDynamicTextBox(value) {
  return '<input name = "DynamicTextBox" type="text" value = "' + value + '" />&nbsp;<input name = "phoneNum" type="text" />&nbsp;<input type="button" value="Remove" class="remove" />';
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="btnAdd" type="button" value="Add" />
<input id="btnRemoveAll" type="button" value="remove all" />
<br />
<br />
<div id="TextBoxContainer">

</div>
<br />
<input id="btnGet" type="button" value="Get Values" />

Related