Search code examples
javascriptinputaddeventlistenerappendchildremovechild

event.target.value, appendChild and removeChild JS


I would like to do a simple program with two buttons, if i click on "+" button i want one input more , if i click "-" i want one input left. I got two input type button (value 0 for plus and 1 for less), and a space (#addSpace) for the new inputs. If i click on value 0 is alright, if i click 0 nothing. The problem in console is: NotFoundError: Node was not found

    HTML
        <div class="d-inline mx-auto" id="addSpace">
            <input name="firstvalue" placeholder="Nome studente">
        </div>

        <div class="d-block pt-5">
            <input type="button" id="aggiungi" value="0"><i class="fas fa-plus"></i>
            <input type="button" id="togli" value="1"><i class="fas fa-less-than"></i>
        </div>

    JS
let add = document.getElementById("aggiungi");
add.addEventListener("click", moreFunction);

let less = document.getElementById("togli");
less.addEventListener("click", moreFunction);
            let space = document.querySelector("#addSpace");

    function moreFunction() {
        let line = document.createElement("input")
        line.classList.add("d-flex");
        line.classList.add("mt-3");

        if (event.target.value == 0) {
            space.appendChild(line);
        }

        if (event.target.value == 1) {
            space.removeChild(line);
        }
    }

Solution

  • How about this solution.

    Every new input you add is given a special class added-input. Then when you click on the "1" button it simply looks for last input with that class.

    let add = document.getElementById("aggiungi");
    add.addEventListener("click", moreFunction);
    
    let less = document.getElementById("togli");
    less.addEventListener("click", moreFunction);
    let space = document.querySelector("#addSpace");
    
    function moreFunction() {
    
        if (event.target.value == 0) {
            let line = document.createElement("input")
            line.classList.add("d-flex");
            line.classList.add("mt-3");
            line.classList.add("added-input");
            space.appendChild(line);
        }
    
        if (event.target.value == 1) {
            const addedInputs = document.querySelectorAll(".added-input");
            if(addedInputs.length){
                addedInputs[addedInputs.length - 1].remove();
            }
        }
    }
    <div class="d-inline mx-auto" id="addSpace">
        <input name="firstvalue" placeholder="Nome studente">
    </div>
    
    <div class="d-block pt-5">
        <input type="button" id="aggiungi" value="0"><i class="fas fa-plus"></i>
        <input type="button" id="togli" value="1"><i class="fas fa-less-than"></i>
    </div>