How can I add multiple inputs to this <div> using javascript function?

Viewed 896

For context, this is a Django based application I am developing. I am using this script within an HTML document. When a button is pressed, it runs the following function. The purpose is to create a element, and then include a couple of inputs and so forth. The problem that I am having is that when I add one input to the div using the following append statements, if I try to add ANOTHER input type (checkbox for example) it over rides the first input (search). How can I append multiple inputs within the script? I will need a total of 3 different inputs.

    var counter = 1; //limits amount of transactions
    function addElements() {
        if (counter < 5) //only allows 4 additional transactions
        {
            let div = document.createElement('div');
            div.id = 'row' + counter;
            document.body.appendChild(div);

            let input = document.createElement('input');
            input.id='search'+counter;
            input.type = 'search';
            input.placeholder = 'Search by product name'
            div.appendChild(input);

            let button = document.createElement('button');
            button.id ='button'+counter;
            button.type = 'QRscan';
            button.innerText = 'QR scan'
            div.appendChild(button);
        }

        counter++
        if (counter >= 6) {
            alert("You have reached the maximum transactions.")
        }
    }
    
    addElements();

1 Answers

If I understood correctly, you just want to append another input to the div. In that case you can just add another input with a different variable name (input1 here) and append it to the div.

var counter = 1; //limits amount of transactions
function addElements() {
    if (counter < 5) //only allows 4 additional transactions
    {
        let div = document.createElement('div');
        div.id = 'row' + counter;
        document.body.appendChild(div);

        let input = document.createElement('input');
        input.id='search'+counter;
        input.type = 'search';
        input.placeholder = 'Search by product name'
        div.appendChild(input);
        
        let input1 = document.createElement('input');
        input.id='checkbox'+counter;
        input.type = 'checkbox';
        div.appendChild(input1);
    
        let button = document.createElement('button');
        button.id ='button'+counter;
        button.type = 'QRscan';
        button.innerText = 'QR scan'
        div.appendChild(button);
    }

    counter++
    if (counter >= 6) {
        alert("You have reached the maximum transactions.")
    }
}
<button onclick="addElements()">
Click me
</button>

Related