Reputation: 5681
I have the following snippet:
var options = [];
$("tr.mks-option-row").each(function (row) {
options.push({
Id: $(row).data("option-id"),
CategoryId: $(row).data("category-id"),
Value: $(row).data("option-text")
});
});
Where .mks-option-row
is the selector for all the rows in a table. The table contains several elements of data, which I have also repeated as data-attributes on the tr
itself.
However, when this snippet is done, the options
array contains n
empty object literals. If there are 4 rows in the table the array contains [{},{},{},{}]
What am I doing wrong here? (I have also tried using quoted identifiers with no difference in outcome)
Upvotes: 0
Views: 72
Reputation: 11102
the row
is passed as the element index in the list of rows to the callback function, you need to use this
in order to fetch the row as jquery object:
var options = [];
$("tr.mks-option-row").each(function () {
options.push({
Id: $(this).data("option-id"),
CategoryId: $(this).data("category-id"),
Value: $(this).data("option-text")
});
});
Update:
More specifically, $.each
expects function(index, element)
. this is one option; ignoring the first argument is another.
$("tr.mks-option-row").each(function (row, element) {
options.push({
Id: $(element).data("option-id"),
CategoryId: $(element).data("category-id"),
Value: $(element).data("option-text")
});
});
Upvotes: 3