Reputation: 116
I have checkboxes in my table rows with an attribute 'result-id'. How do I fill a javascript array with the values stored in 'result-id' checkbox, inside the table row.
I already figured out how to acces the data in jquery, now I just want to store that data inside of an array.
It looks a little something like this :
<td>
<input result-id="@item.Id" type="checkbox" />
</td>
This is the jquery I have now, it only adds one item (last clicked checkbox id)
$(tableBody).find('tr').each(function () {
if ($(this).find('input:checkbox').prop("checked") == true) {
resultList.fill(parseInt($(this).find('input:checkbox').attr('result-id')));
}
});
Upvotes: 1
Views: 78
Reputation: 1075915
You'd want to:
:not(:checked)
, or .filter
, ...)map
on the result to get a jQuery set containing the result-id
values (by returning this.getAttribute("result-id")
or $(this).attr("result-id")
)get
on it to get the actual arrayFor instance:
var array = $(tableBody).find("tr input:checkbox:not(:checked)")
.map(function() {
return this.getAttribute("result-id");
})
.get();
That uses the jQuery-specific :checked
pseudo-class to only look at checked checkboxes, and uses the DOM directly to get the attribute value.
You could also do it without using a jQuery-specific selector:
var array = $(tableBody).find("tr input[type=checkbox")
.filter(function() { return this.checked; })
.map(function() {
return this.getAttribute("result-id");
})
.get();
Or without using jQuery at all (here I'm assuming tableBody
is a DOM element, not a jQuery set, and a modern browser):
const array = Array.from(tableBody.querySelectorAll("tr input[type=checkbox"))
.filter(({checked}) => checked)
.map(cb => cb.getAttribute("result-id"));
Upvotes: 2