Richard Payne
Richard Payne

Reputation: 303

Dynamically generate multiple elements

I am trying to use JavaScript to generate a set amount of input box's dependent on the users input. However, when I do so with a for loop it just generates one input box and appends said input box a set amount of time.

function generateAttributes(){
    var y = 1;
    var mAttributes = document.getElementById('numAttributes').value;
    var parent = document.getElementsByTagName('div')[17];
    var inputBox = document.createElement('input');
    inputBox.setAttribute('class', 'form-control');
    for(var i = 0; i < mAttributes; i++){
        inputBox.setAttribute('id', y);
        inputBox.setAttribute('placeholder', 'Attribute ' + y);
        parent.appendChild(inputBox);
        y++;
    }

}

Upvotes: 0

Views: 41

Answers (1)

charlietfl
charlietfl

Reputation: 171679

You need to create a new element for each iteration of the loop.

Move the following inside the loop:

var inputBox = document.createElement('input');
    inputBox.setAttribute('class', 'form-control');

Result:

for(var i = 0; i < mAttributes; i++){

    var inputBox = document.createElement('input');
    inputBox.setAttribute('class', 'form-control');
    inputBox.setAttribute('id', y);
    inputBox.setAttribute('placeholder', 'Attribute ' + y);
    parent.appendChild(inputBox);
    y++;
}

You are currently creating only one element and modifying and appending that same element over and over

Upvotes: 1

Related Questions