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>

2
  • stackoverflow.com/questions/9454645/… 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. Commented Jan 3, 2020 at 16:27
  • ID MUST BE UNIQUE Commented Jan 3, 2020 at 16:27

1 Answer 1

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(),
  ];
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.