To directly answer your problem, you should use +=
instead of =
when you add new HTML into it because by using =
, you are overriding existing child elements inside it (deleting them).
So by using +=
, you are just appending after existing child elements instead of overriding them.
function add_input() {
var s = document.getElementById('ref').value;
var i = 0;
while (i < s) {
document.getElementById('the_list').innerHTML += '<p><input type="text" name="holder_'+ i +'" /></p>';
i++;
}
}
<input type="number" name="ref" id="ref" onchange="add_input();">
<div id="the_list"></div>
Better yet, you should use DOM method appendChild
directly instead of adding raw HTML:
function add_input() {
var theList = document.getElementById('the_list');
var s = document.getElementById('ref').value;
var i = 0;
var p;
var input;
while ( i < s) {
p = document.createElement('p');
input = document.createElement('input');
input.setAttribute('type', 'text');
input.setAttribute('name', 'holder_' + i);
p.appendChild(input);
theList.appendChild(p);
i++;
}
}
<input type="number" name="ref" id="ref" onchange="add_input();">
<div id="the_list"></div>