Reputation: 422
I am trying to make a calculator that displays a certain number of input text fields based on a number entered earlier (variable). For example:
How many whatever? (text field that inputs to a variable)
How should I make the page (onBlur
) generate a number of text fields based on the user's number?
Upvotes: 1
Views: 1357
Reputation: 1930
jQuery Version of Mosh Feu's Version
Javascript Part:
function addInputs(elm) {
var html = '';
for (var i = 0; i < parseInt($(elm).val()); i++) {
html += '<input type="text" placeholder="Textfield '+i+'">';
}
$('#result').html(html);
}
HTML Part:
<input type="text" onblur="addInputs(this)" placeholder="Type a numder" />
<div id="result"></div>
Upvotes: 1
Reputation: 29277
function addInputs(elm) {
var result = document.querySelector('#result');
result.innerHTML = '';
for (var i = 0; i < parseInt(elm.value); i++) {
var wrapper = document.createElement('div');
wrapper.innerHTML = '<input type="text" placeholder="textfield ' + i + '" />';
result.appendChild(wrapper);
}
}
div {
margin-top:5px;
}
<input type="text" onblur="addInputs(this)" placeholder="Type a numder" />
<div id="result"></div>
Upvotes: 3