user10786952
user10786952

Reputation:

Better way to code rather than using whole new code with `insertAdjacentHTML`

I am trying to add new input and button when clicking certain button.

<div class="form-group row">
    <label>...</label>
    <div class="col-sm-9 input-group" id="aa">
        <input class="form-control mr-2" id="bbb" name="bbb" required type="text">
        <div class="input-group-append">
           <button type="button" class="btn btn-block btn-outline-info float-right" onclick="add()">Add</button>
        </div>
     </div>
</div>

Here is my question.

  1. By clicking on button, I want to add same input and button under input(id="aa"). And every time when clicking on new button I want to add new input and button again.

    • I tried to solve by using insertAdjacentHTML. But this requires long whole new code. So wondering if there is more simple way to add new input and button.

    ※ Code I am trying to add

    <div class="col-sm-9 input-group" id="aa"> <input class="form-control mr-2" id="bbb" name="bbb" required type="text"> <div class="input-group-append"> <button type="button" class="btn btn-block btn-outline-info float-right" onclick="add()">Add</button> </div> </div>

  2. Next I am trying to change adding button to delete button when new input and button is clicked. Can use remove method. But I need each id of new input and button. So wondering if there is specific way to assign different id to new input and button every time I add one?

Hope someone can show me at least where I can refer to.

Upvotes: 1

Views: 37

Answers (1)

mplungjan
mplungjan

Reputation: 177684

Don't use the ID, use relative addressing, parentNode, closest etc. And use cloneNode to get the stuff you want to duplicate

Note, you do need "new long code" for this

window.addEventListener("load",function() {
  document.addEventListener("click",function(e) { // delegation
    var elem = e.target;
    if (elem.className.indexOf("btn") == 0) {
      var div = elem.closest("div.form-group");
      if (elem.innerText=="Add") {
        var newDiv = div.cloneNode(true);  // deep cloning
        newDiv.querySelector(".btn").innerText="Del";
        // here you may want to rename the input field too
        div.parentNode.appendChild(newDiv);
      }
      else {
        div.parentNode.removeChild(div);
      }
    }
  });
});
<div class="form-group row">
    <label>...</label>
    <div class="col-sm-9 input-group">
        <input class="form-control mr-2" name="bbb" required type="text">
        <div class="input-group-append">
           <button type="button" class="btn btn-block btn-outline-info float-right">Add</button>
        </div>
     </div>
</div>

Upvotes: 0

Related Questions