简体   繁体   中英

How could I display a certain number of input fields based on a variable?

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?

 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> 

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM