Hai Yaa
Hai Yaa

Reputation: 7

How to insert multiple element into an array in JQuery?

I make a table in a form to enable user to submit several item in one time. I am able to use jquery to get the first row of the value input by user. But when they type in the value in the second row, it show error. I am pretty sure there is something wrong with the array that I am using. I have try 2 methods, both method work but it only takes the value from first row only.

<form>
<table>
<thead>
<tr>
 <th>Item Code</th>
 <th>Item Name</th>
 <th>Status</th>
</tr>
</thead>
<tbody id="entrybody">
<tr>
 <td><input type="text" name="prd_code"></td>
 <td><input type="text" name="prd_name"></td>
 <td><input type="text" name="prd_cond"></td>
</tr>
<tr>
 <td><input type="text" name="prd_code"></td>
 <td><input type="text" name="prd_name"></td>
 <td><input type="text" name="prd_cond"></td>
</tr>
<tr>
 <td><input type="text" name="prd_code"></td>
 <td><input type="text" name="prd_name"></td>
 <td><input type="text" name="prd_cond"></td>
</tr>
</tbody>

</table>
</form>
$(function() {
    $.post("action.php", function(data) {
        $("[name='title']").val(data.title);
        $("[name='body']").val(data.body);
    }, "json");
    setInterval(function() {
        var itemlist = new Array;
        var count = 1;

        var title = $("[name='title']").val();
        var body = $("[name='body']").val();

        itemlist[count - 1] = {};

        $("#productbody tbody tr").each(function() {
            var that = $(this);
            if (that.find("[name='prd_code']").val().length !== 0) {
                /*itemlist.push(code);
                itemlist.push(name);
                itemlist.push(cond);*/ //method 1

                itemlist[count - 1].code = that.find("[name='prd_code']").val();
                itemlist[count - 1].name = that.find("[name='prd_name']").val();
                itemlist[count - 1].cond = that.find("[name='prd_cond']").val(); //method 2

                count++;
            }
        });

        console.log(itemlist);

    }, 2000);
});
===== Console message (first row) =====
0:
code: "test_code1"
cond: "test_status1"
name: "test_name1"

Upvotes: 0

Views: 1176

Answers (2)

KooiInc
KooiInc

Reputation: 122906

As far as I understand you want to create an array of the values from all table cells in all rows. Here is a relative simple way to do this without JQuery.

document.addEventListener(`change`, handle);

function handle(evt) {
  if (evt.target.name.startsWith(`prd_`)) {
    // retrieve all rows
    const values = [...document.querySelectorAll(`tbody tr`)]
      // map to objects containing row number and values
      .map(row => ({
         row: row.rowIndex,
         values: [...row.querySelectorAll(`[name^='prd_']`)]
            .reduce( (acc, val) => ({...acc, [val.name]: val.value}), {})
        }))
      .filter(val => (val.values.prd_code || ``).trim().length > 0);
      
    document.querySelector(`pre`).textContent = JSON.stringify(values, null, 2);
  }
}
<table>
  <thead>
    <tr>
      <th>Item Code</th>
      <th>Item Name</th>
      <th>Status</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><input type="text" name="prd_code"></td>
      <td><input type="text" name="prd_name"></td>
      <td><input type="text" name="prd_cond"></td>
    </tr>
    <tr>
      <td><input type="text" name="prd_code"></td>
      <td><input type="text" name="prd_name"></td>
      <td><input type="text" name="prd_cond"></td>
    </tr>
    <tr>
      <td><input type="text" name="prd_code"></td>
      <td><input type="text" name="prd_name"></td>
      <td><input type="text" name="prd_cond"></td>
    </tr>
  </tbody>
</table>

<pre></pre>

Upvotes: 0

I've changed the method of the event to a .change() for this example.

Then I've changed the following code:

var itemlist = new Array;

var title = $("[name='title']").val();
var body = $("[name='body']").val();
$("#productbody  tbody tr").each(function(i) {
  var that = $(this);
  if (that.find("[name='prd_code']").val().length !== 0) {
    itemlist[i] = {};
    itemlist[i].code = that.find("[name='prd_code']").val();
    itemlist[i].name = that.find("[name='prd_name']").val();
    itemlist[i].cond = that.find("[name='prd_cond']").val(); //method 2
  }
});

One problem was that you use this itemlist[count - 1] = {}; before your foreach statement. so you only created the first object.

Demo

$(function() {
  $("#productbody  tbody tr input").change(function() {
    //setInterval(function() {
    var itemlist = new Array;

    var title = $("[name='title']").val();
    var body = $("[name='body']").val();
    $("#productbody  tbody tr").each(function(i) {
      var that = $(this);
      if (that.find("[name='prd_code']").val().length !== 0) {
        itemlist[i] = {};
        itemlist[i].code = that.find("[name='prd_code']").val();
        itemlist[i].name = that.find("[name='prd_name']").val();
        itemlist[i].cond = that.find("[name='prd_cond']").val(); //method 2
      }
    });

    console.log(itemlist);
  });
  //}, 2000);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
  <table id="productbody">
    <thead>
      <tr>
        <th>Item Code</th>
        <th>Item Name</th>
        <th>Status</th>
      </tr>
    </thead>
    <tbody id="entrybody">
      <tr>
        <td><input type="text" name="prd_code"></td>
        <td><input type="text" name="prd_name"></td>
        <td><input type="text" name="prd_cond"></td>
      </tr>
      <tr>
        <td><input type="text" name="prd_code"></td>
        <td><input type="text" name="prd_name"></td>
        <td><input type="text" name="prd_cond"></td>
      </tr>
      <tr>
        <td><input type="text" name="prd_code"></td>
        <td><input type="text" name="prd_name"></td>
        <td><input type="text" name="prd_cond"></td>
      </tr>
    </tbody>

  </table>
</form>

Upvotes: 1

Related Questions