Jenny
Jenny

Reputation: 919

Add multiple input values into textarea on submit

I have a couple of input fields, the number of input fields vary based on a user entered input field. If the user enters 1 then 20 text fields and 20 emails display, if they enter 2 then 40 text fields and 40 email fields display and so on. On submission of the form I need these fields to be added to the textarea field separated by a comma. It is similar to what was done here: Re-posting <input> value into <textarea> but due to the large number of possible fields I can't add each input as a variable. Is there an efficient way to do this considering there could be so many fields? TIA.

<div id="sponsor">
    <input type="text">
    <input type="email">
</div>

<textarea></textarea>

Upvotes: 1

Views: 809

Answers (1)

Karan
Karan

Reputation: 12629

I hope all of your input will be under div with id sponsor.

  1. So you can select all the inputs with selector $("#sponsor input").
  2. Get their values with .toArray().map(x => x.value).
  3. And join them with , by .join(",")
  4. Set id to textarea so you can assign value to it.

Note : If you are having other inputs also inside sponsor which shouldn't included then you have to add class to your inputs which you want to include and use class selector to get list. Suppose we add a class input then use $('.input') instead of $("#sponsor input").

You can test it below.

function submit() {
  var commaSeparatedValues = $("#sponsor input").toArray().map(x => x.value).join(",");      
  $("#list").val(commaSeparatedValues);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>

<div id="sponsor">
    <input type="text">
    <input type="email">
</div>

<textarea id="list"></textarea>
<input type="button" value="submit" onclick="submit()">

Upvotes: 2

Related Questions