3

I'm new in javaScript and don't now how to realize this. I have 'select' with numbers in my HTML.

<select class="form-control"  id="select" >
    <option>1</option>
    <option>2</option>
    <option>3</option>
</select>

When user will choose the number in this select, js will create as many input fields as the user chooses,like on this picture [

enter image description here

How to do this?

Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
  • 2
    Welcome to Stack Overflow. Please read ["How to ask a question"](https://stackoverflow.com/help/how-to-ask). We ask that you research your issue as best you can before posting. In your case, you need to know how to do several things to make your scenario work (set up event handlers, create new DOM elements, update the DOM). You should investigate these things and then make an attempt at a solution. If you get stuck, come back and post what you've done and what you are stuck on. But, we don't just supply answers to questions where no attempt has been made. Good luck! – Scott Marcus Sep 22 '18 at 19:53
  • 4
    Possible duplicate of [Adding input elements dynamically to form](https://stackoverflow.com/questions/14853779/adding-input-elements-dynamically-to-form) – Tarabass Sep 22 '18 at 19:53

2 Answers2

2

This is just to give you an idea of how to do it.

addImputs(select);


select.addEventListener("change", ()=>{
  
  addImputs(select);
  
})

function addImputs(select){
 let num = parseInt(select.options[select.selectedIndex].value);
  imputs.innerHTML = "";
  for(let i = 0; i < num; i++){
  let imp = document.createElement("input");
  imp.setAttribute("type", "text");
  imputs.appendChild(imp)
}
}
<select class="form-control"  id="select" >
    <option>1</option>
    <option>2</option>
    <option>3</option>
</select>

<div id="imputs"></div>
enxaneta
  • 31,608
  • 5
  • 29
  • 42
1

Something like this may help

function createFileds(ele) {
  let form = document.getElementById("form");
  form.innerHTML = '';
  for(let i = 0; i < ele.value; i++) {
    form.innerHTML += '<Input name="input ' + i + '">';
  }
}
<select class="form-control"  id="select" onchange="createFileds(this)">
    <option>1</option>
    <option>2</option>
    <option>3</option>
</select>

<form id="form"></form>
  
Suman Kundu
  • 1,702
  • 15
  • 22