Miguel Flores Miguel Flores - 29 days ago 7
Javascript Question

Draw 'N' inputs depending value from select

I'm trying to draw an specific number of inputs, this number depends of the value from select input, the problem here is that the selected option is determinated by the value from another number input, in other words if I type

3
on my numeric input, the selected option of my select input should be
3
, as a result of this my function should draw
3
inputs. Maybe I'm not much clear but here is my code and what I tried:



$(document).ready(function() {
$('#Controls').on('blur', '#InputNumbers', function() {
selectValue();
});
});

function selectValue() {
var inputVal = $('#InputNumbers').val();

$('#MyInputs').val(inputVal);
$('#MyInputs').change(function() {
draw();
});
}

function draw() {
alert("Hi");
var total = $('#MyInputs').val();
var html = "";
for (var i = 0; i < total; i++) {
html += '<input />';
}

$('#draw').html(html);

}

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


<div id="Controls">
<input type="number" placeholder="Number of inputs" id="InputNumbers" />

<select id="MyInputs" disabled>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>

<div id="draw">
</div>

</div>





As you can see first 2 steps works fine, the problem is when I tried to do this:

$('#MyInputs').change(function() {
draw();
});


The function is not executed, how can I solve this?

Answer

Please refer below code, how its working, You don't need change event

$(document).ready(function() {
  $('#Controls').on('blur', '#InputNumbers', function() {
    selectValue();
  });
});

function selectValue() {
 
  var inputVal = $('#InputNumbers').val();

  $('#MyInputs').val(inputVal);
 
    draw();
  
}

function draw() {
  alert("Hi");
  var total = $('#MyInputs').val();
  alert(total)
  var html = "";
  for (var i = 0; i < total; i++) {
    html += '<input />';
  }

  $('#draw').html(html);

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


<div id="Controls">
  <input type="number" placeholder="Number of inputs" id="InputNumbers" />

  <select id="MyInputs" disabled>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
</select>

  <div id="draw">
  </div>

</div>