0

I designed a comment section with a reply. I want a comment form to be created under the same comment when the user clicks on the reply button. I wrote this myself, but when I click on the reply button, the form is created only for the first comment.

function addtextbox() {
  // Create a form dynamically.
  var form = document.createElement("form");
  
  form.setAttribute("method", "post");
  form.setAttribute("action", "submit.php");

  // Create an input element for replyText.
  var ID = document.createElement("input");
  
  ID.setAttribute("type", "text");
  ID.setAttribute("name", "body");
  ID.setAttribute("placeholder", "Your Comment");
  form.append(ID);
  document.getElementsByClassName('formbox')[0].appendChild(form);
}
<button onclick="addtextbox()">reply</button>
<div class="formbox"></div>
Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
mahdi sna
  • 36
  • 6
  • 1. Replace HTML with `
    ` 2. use `function addtextbox(btn) {` 3. instead of explicitly appending to the first formbox div, use `btn.parentNode.append(form);` (note that this is a quick and dirty fix but I'm too lazy to write another reply to "handle clicks on a list correctly")
    –  Sep 18 '21 at 11:53
  • Inline event handlers like `onclick` are [not recommended](/q/11737873/4642212). They are an [obsolete, hard-to-maintain and unintuitive](/a/43459991/4642212) way of registering events. Always [use `addEventListener`](//developer.mozilla.org/docs/Learn/JavaScript/Building_blocks/Events#inline_event_handlers_%E2%80%94_dont_use_these) instead. _“the form is created only for the first comment”_ — Which one is “the first comment”? Your HTML doesn’t contain any comment. Familiarize yourself with the [DOM API](//developer.mozilla.org/docs/Web/API/Document_Object_Model). – Sebastian Simon Sep 18 '21 at 11:55
  • because you always append the form to the first ```formbox``` you need to pass replay or find the parent of addtextbox button and append the form inside it – Moufeed Juboqji Sep 18 '21 at 11:57

1 Answers1

1

there is a lot of way, but this is the simplest. good luck ;)

        const replayButtons = document.querySelectorAll('.replay');
        
        replayButtons.forEach(item => {
            item.addEventListener('click', () => {
                item.parentElement.insertAdjacentHTML('beforeend', `
                    <input type="text" placeholder="write your replay" />
                `);
            });
        })
    <div>
        <h1>Post1</h1>
        <p>Lorem ipsum dolor sit.</p>
        <br>
        <button class="replay">Replay</button>
        <br>
    </div>
    <div>
        <h1>Post2</h1>
        <p>Lorem ipsum dolor sit.</p>
        <br>
        <button class="replay">Replay</button>
        <br>
    </div>
    <div>
        <h1>Post3</h1>
        <p>Lorem ipsum dolor sit.</p>
        <br>
        <button class="replay">Replay</button>
        <br>
    </div>