Omar Ruder
Omar Ruder

Reputation: 116

How do I fill javascript array with HTML attributes?

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

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075915

You'd want to:

  • Filter out the unchecked checkboxes (:not(:checked), or .filter, ...)
  • Use 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"))
  • Use get on it to get the actual array

For 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

Related Questions