0

I got a form where I want to dynamically add input fields, if the users clicks on a "add more" button. At the moment it works to create the buttons on click, but the buttons do no get created at the position where I want them to be. Here is my HTML Code Snippet:

window.addEventListener("load", function() {
  var addMoreButtons = document.querySelectorAll("#add-more1, #add-more2");
  addMoreButtons.forEach(function(button) {
    button.addEventListener("click", function() {
      console.log(button);
      // Create a div
      var div = document.createElement("div");

      // Create a text input
      var text = document.createElement("input");
      text.setAttribute("type", "text");
      text.setAttribute("name", "More");
      text.setAttribute("placeholder", "Weitere hinzufügen");

      // add the file and text to the div
      div.appendChild(text);

      //Append the div to the container div
      document.querySelector(".buttonTest").appendChild(div);
    });
  });
});
<div class="user-details">
  <div class="input-box">
    <span class="details">Stärken</span>
    <input type="text" placeholder="Stärken, z.B. 'Kommunikativ'" id="strenghts">
    <div class="buttonTest">
      <button type="button" class="add-more" id="add-more1">+ Weitere 
                    hinzufügen</button>
    </div>
  </div>
  <div class="input-box">
    <span class="details">Technische Fähigkeiten</span>
    <input type="text" placeholder="Technische Fähigkeiten, z.B. 'JavaScript'" id="tech">
    <div class="buttonTest">
      <button type="button" class="add-more" id="add-more2">+ Weitere hinzufügen</button>
    </div>
  </div>
</div>

Now every time when the first (#add-more1) or second (#add-more2) button is clicked, the input field gets created below the first button. But I want the input fields to appear where the button was clicked. For example: If the first button is clicked I want the input field to be created below the first button. And if the second button is clicked I want the input field to be created below the second button and not below the first button.

Thanks for your help! :)

2 Answers 2

2

I have simplified and enhanced your code somewhat, using event delegation and [element].insertAdjacentElement to add a text input element at the desired position.

For the new text input element a clone of the old one is used and placed within a new div. After the cloned input element a 'minus' button is placed (it is also handled by the handle function).

Using insertAdjacentElement gives you control over the placement of the new element (here: after the span containing the clicked button, cf afterend).

document.addEventListener(`click`, handle);

function handle(evt) {
  const bttnElem = evt.target.closest(`.buttonTest, .added`);
  
  if (bttnElem?.classList.contains(`added`)) {
    return bttnElem.remove();
  }
  
  if (bttnElem) {
    const bttnRoot = bttnElem.closest(`.input-box`);
    const addBttn = bttnRoot.querySelector(`button`);
    const inputElemCopy = bttnRoot.querySelector(`input`).cloneNode(true);
    const text = bttnRoot.querySelector(`.details`).textContent;
    const nwDiv = document.createElement(`div`);
    nwDiv.classList.add(`added`);
    inputElemCopy.name = `${inputElemCopy.id}_more`;
    inputElemCopy.removeAttribute(`id`);
    const removeBttn = addBttn.cloneNode(true);
    removeBttn.title = `Entfernen`;
    removeBttn.textContent = ` - `;
    removeBttn.className = ``;
    nwDiv.append(text + ` `, inputElemCopy, ` `, removeBttn);
    bttnElem.insertAdjacentElement(`afterend`, nwDiv);
  }
}
.user-details {
  font: normal 14px / 19px verdana, arial, sans-serif;
  
  div.input-box {
    margin: 0.2rem 0;
    padding: 0.5rem;
    border: 1px solid #c0c0c0;
    
    div {
      margin: 0.2rem 0;
    }
    
    button {
      font-family: monospace;
      margin-left: 0.2rem;
    }
  }
}
<div class="user-details">
  <div class="input-box">
    <span class="details">Stärken</span>
    <input type="text" placeholder="Stärken, z.B. 'Kommunikativ'" 
      id="strenghts">
    <span class="buttonTest">
      <button type="button" class="add-more" id="add-more1"
        title="Weitere hinzufügen"> + </button>
    </span>
  </div>
  <div class="input-box">
    <span class="details">Technische Fähigkeiten</span>
    <input type="text" placeholder="Technische Fähigkeiten, z.B. 'JavaScript'" 
      id="tech">
    <span class="buttonTest">
      <button type="button" class="add-more" id="add-more1"
        title="Weitere hinzufügen"> + </button>
    </span>
  </div>
</div>

Sign up to request clarification or add additional context in comments.

Comments

1

You need to use parentElement

https://www.w3schools.com/jsref/prop_node_parentelement.asp

Example:

window.addEventListener("load", function() {
  var addMoreButtons = document.querySelectorAll("#add-more1, #add-more2");
  addMoreButtons.forEach(function(button){
    button.addEventListener("click", function() {
        console.log(button);
      // Create a div
      var div = document.createElement("div");
  
      // Create a text input
      var text = document.createElement("input");
      text.setAttribute("type", "text");
      text.setAttribute("name", "More"); 
      text.setAttribute("placeholder", "Weitere hinzufügen");
  
      // add the file and text to the div
      div.appendChild(text);
  
      //Append the div to the container div
      button.parentElement.appendChild(div);
    });
  });
});
<div class="user-details">
            <div class="input-box">
                <span class="details">Stärken</span>
                <input type="text" placeholder="Stärken, z.B. 'Kommunikativ'" id="strenghts">
                <div class="buttonTest">
                    <button type="button" class="add-more" id="add-more1">+ Weitere 
                    hinzufügen</button>
                </div>
            </div>
            <div class="input-box">
                <span class="details">Technische Fähigkeiten</span>
                <input type="text" placeholder="Technische Fähigkeiten, z.B. 'JavaScript'" id="tech">
                <div class="buttonTest">
                    <button type="button" class="add-more" id="add-more2">+ Weitere hinzufügen</button>
                </div>
            </div>
         </div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.