websmentor.com websmentor.com - 4 months ago 7
Javascript Question

Dynamically generate textbox when user enters something

Initially i have one textbox/selectbox when user enters something or selects something generate another textbox/selectbox and also i can set limit how many textbox/selectbox can be generated.

please advice me how can i achieve this

Answer

You can use jQuery append() method to create html dynamically.

$("#ddlOptions").on("change", function(e) {

  var len = $('.txtInput').length;
  if (len == 0) {
    $('.container').append('<br> <input type="text" id=txtTextBox_' + len + ' class="txtInput" /> <br>');
  }
});

$(document).on("change", '.txtInput', function() {
  var len = $('.txtInput').length;
  
  if ($(this).val() != "") {
    $('.container').append('<br> <input type="text" id=txtTextBox_' + len + ' class="txtInput" /> <br>');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <select id="ddlOptions">
    <option>option 1</option>
    <option>option 2</option>
    <option>option 3</option>
    <option>option 4</option>
  </select>
</div>