1

I have developed dynamically created text boxes by clicking a button using AJAX. I have three text box IDs such as morning, noon and night. I just want to store these values in an array like [morning, noon, night][morning, noon, night]...

I have tried, but it stored like [morning, morning, noon, noon, night, night]. I can't understand how to separate as I mentioned above.

Please help me to solve my problem.

$(document).ready(function() {
  $(document).on('click', '#submit', function() {
    var modess = [
      $("input[id='morning[]']").map(function() {
        return $(this).val();
        console.log(morning);
      }).get(),

      $("input[id='noon[]']").map(function() {
        return $(this).val();
        console.log(noon);
      }).get(),

      $("input[id='night[]']").map(function() {
        return $(this).val();
        console.log(night);
      }).get(),
    ]

    alert(modess);

    const medic = [...morning, ...noon, ...night];
    console.log(medic);
    var medical = JSON.stringify(medic);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table table-bordered mb-0" id="medical">
  <thead>
    <tr>
      <th>Medicine Name</th>
      <th>Morning</th>
      <th>Noon</th>
      <th>Night</th>
      <th>charge</th>
      <th> <button type="button" name="add" id="add" class="btn btn-success btn-xs"> + </button> </th>
    </tr>
  </thead>
  <tbody id="rows"></tbody>
</table>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • https://stackoverflow.com/questions/9454645/does-id-have-to-be-unique-in-the-whole-page You should avoid non-web standard compliant code. Rather than using an attribute selector to get around the uniqueness expectations of ids, use classes instead. – Taplar Jan 03 '20 at 16:27
  • **ID MUST BE UNIQUE** – Mister Jojo Jan 03 '20 at 16:27

1 Answers1

2

The issue is because you're grouping by input, not by row in the table.

Also note that you appears to be using the same id on multiple elements, which is invalid. They have to be unique. Use a common class on them all instead. Then you can use map() to select the values from those fields like this:

let modess = $('#rows tr').map(function() {
  let $tr = $(this);
  return [
    $tr.find('.morning').val(),
    $tr.find('.noon').val(),
    $tr.find('.night').val(),
  ];
});
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339