Miguel Flores Miguel Flores - 1 month ago 9
Javascript Question

How to get the value from N dynamic inputs

I have a select with an options, this options have the number of inputs that user want to draw, after that user can type information in that inputs and finally they have to click a button to display that values, right now I'm doing this like this:

var value1 = $('#Input1').val();


The problem here is that the user can create a maximum of 200 inputs, so if I keep doing this in the above way I'll need to do that with the 200 inputs and it's a lot of code lines, my question is if exits a way to get the value of N inputs, I draw the inputs dynamically with a for loop, so all the input ID is something like
Input(MyForVariable), Input1, Input2... etc
, so maybe I'm thinking in create another loop to get the value of that inputs, here is my code:



$(document).ready(function () {
$('#sel').change(function () {
draw();
});

$('#btn').click(function () {
show();
});
});

function draw() {
var selected = $('#sel').val();
var html = "";

for (i = 1; i <= selected; i++) {
html += '<input type="text" id="Imput' + i + '" />';
}
$('#forms').html(html);
}

function show() {
var total = $('#sel').val();

if (total == 2) {
var val1 = $('#Imput1').val();
var val2 = $('#Imput2').val();

alert(val1 + val2);
}

if (total == 3) {
var val1 = $('#Imput1').val();
var val2 = $('#Imput2').val();
var val3 = $('#Imput3').val();

alert(val1 + val2 + val3);
}
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>



<select id="sel">
<option value="2">A</option>
<option value="3">B</option>
<option value="4">C</option>
<option value="5">D</option>
</select>

<div id="forms">
</div>

<button id="btn">Click</button>




Answer

Put all your inputs inside a container, and loop through them:

$('#add').on('click', function () {
  $('<input />').appendTo('#myinputs');
});


$('#get').on('click', function () {
  var values = [];
  
  $('#myinputs input').each(function () {
    values.push(this.value);
  });
  
  console.log(values);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<div id="myinputs">
  <input />
</div>

<button id="add">Add another input</button>

<hr />

<button id="get">Get values</button>

Comments