Pages

on button click add text boxes and delete script

  <button onclick="addField()" class="btn btn-outline-primary mb-3 btn-sm" type="button">+ Add Field</button>


                        <div id="fieldSection" class="mb-3"></div>


let fieldCount = 0;


function addField() {

    fieldCount++;


    const textboxName = `newfield_${fieldCount}`;


    const textbox = document.createElement("input");

    textbox.type = "text";

    textbox.name = textboxName;

    textbox.classList.add("form-control", "mb-2");


    // Remove button


    const removeBtn = document.createElement("button");

    removeBtn.textContent = "X";

    removeBtn.classList.add("btn", "btn-sm", "btn-outline-danger");

    removeBtn.addEventListener("click", () => {

        removeField(textboxName);

    });


    const fieldContainer = document.createElement("div");

    fieldContainer.classList.add("fieldContainer");

    fieldContainer.appendChild(textbox);

    fieldContainer.appendChild(removeBtn);


    const fieldSection = document.getElementById("fieldSection");

    fieldSection.appendChild(fieldContainer);

}


function removeField(textboxName) {

    const removable = document.querySelector(`input[name="${textboxName}"]`).parentNode;


    const fieldSection = document.getElementById("fieldSection");

    fieldSection.removeChild(removable);

}

No comments:

Post a Comment

Search This Blog