tushar
tushar

Reputation: 23

How to add new elements to a jQuery object which already contains some elements

supplieritemdata is my object and data is an array. I want to add elements to the object as the checkbox checked find to be true.

My problem is that the object only holds the last values provided to it, not all the values. I want to store all the values.

var supplieritemdata = {},
  data = [];

$('#tbl1 > tbody  > tr').each(function(index, tr) {
  debugger
  // var row = $(this).closest("tr");
  var ch = $(this).find(".check").prop("checked");
  if (ch) {
    supplieritemdata.SupplierId = $('#ddlsupplierdetails').val();
    supplieritemdata.ItemCategoryId = $('#ddlcategory').val();
    supplieritemdata.ItemGroupId = $('#ddlgroup').val();
    supplieritemdata.ItemId = $(this).find(".label-info").html();
  }

  data.push(supplieritemdata);
  //supplieritemdata = null;
  // $(this).prop("checked")
  // $this.find("input.name").val();
});

Upvotes: 1

Views: 69

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337560

The issue is because you're amending the same reference to supplieritemdata in the iteration. This means that, although you've added that variable to the data array, setting it to null, or updating its properties will affect the instance held in the array. As such, you overwrite the properties of the single object in every iteration of the loop. This is why only the last values are shown.

To fix this you need to create a new object within each iteration of the loop.

Also note that the logic can be made more succinct by only selecting tr elements which have a checked checkbox (to remove the need for the if) and als by using map(). Try this:

var data = $('#tbl1 > tbody  > tr:has(:checkbox:checked)').map(function() {
  return {
    SupplierId: $('#ddlsupplierdetails').val(),
    ItemCategoryId: $('#ddlcategory').val(),
    ItemGroupId: $('#ddlgroup').val(),
    ItemId: $(this).find(".label-info").html()
  }
}).get();

console.log(data);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="ddlsupplierdetails" value="ddlsupplierdetails" />
<input type="text" id="ddlcategory" value="ddlcategory" />
<input type="text" id="ddlgroup" value="ddlgroup" />
<input type="text" id="ddlsupplierdetails" value="ddlsupplierdetails" />

<table id="tbl1">
  <tbody>
    <tr>
      <td><input type="checkbox" class="check" checked="true" /></td>
      <td><span class="label-info">Foo bar 1</span></td>
    </tr>
    <tr>
      <td><input type="checkbox" class="check" /></td>
      <td><span class="label-info">Foo bar 2</span></td>
    </tr>
    <tr>
      <td><input type="checkbox" class="check" checked="true" /></td>
      <td><span class="label-info">Foo bar 3</span></td>
    </tr>
  </tbody>
</table>

Upvotes: 1

Related Questions