1

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')));
            }
        });

1 Answer 1

2

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"));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.