Jenny
Jenny

Reputation: 919

How can I multiply user input to create additional fields?

I would like to multiply the value that is entered in the userInput field by 20 so that the fields with class xafields display 20 times what is entered in the userInput. (Enter 1, 20 of each field is added, enter 2, 40 of each field is added, etc.).

jQuery("#userInput").change(function() {
  var htmlString = "";
  var len = jQuery(this).val();
  for (var i = 0; i <= len; i++) {

    htmlString += 'Name<br /><input class="xafields" type="text"><br />';
    htmlString += 'Email<br /><input class="xafields"><br /><br />';

  }
  jQuery("#xafieldContainer").html(htmlString);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="userInput">
<div id="xafieldContainer"></div>

Upvotes: 1

Views: 33

Answers (1)

StudioTime
StudioTime

Reputation: 23979

Have a look at the changes and comments in the code:

Simply multiply the value entered by 20.

Make sure you start from one in the loop, not zero

jQuery("#userInput").change(function() {
  var htmlString = "";
  var len = jQuery(this).val() * 20; /* Multiply value entered by 20 */
  for (var i = 1; i <= len; i++) { /* <-- start at 1, not 0 */

    htmlString += 'Name<br /><input class="xafields" type="text"><br />';
    htmlString += 'Email<br /><input class="xafields"><br /><br />';

  }
  jQuery("#xafieldContainer").html(htmlString);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="userInput">
<div id="xafieldContainer"></div>

Upvotes: 1

Related Questions