Daniel
Daniel

Reputation: 107

How to get ID of checked checkboxes from foreach loop

I have a foreach loop creating a checkbox for each record from a table in my Db as follows:

@foreach (var item in Model)
{
    <input id="@item.extras_id" name="@item.extra_name" type="checkbox" value="@item.rate" /> 
    <span>@item.extra_name</span>
    <span style="float: right; padding-right: 16px;">R @item.rate.00</span>
    <br />
}

My question is, Is there a way from me to retrieve the ID's of all checked checkboxes?

Upvotes: 0

Views: 1771

Answers (2)

jonatjano
jonatjano

Reputation: 3728

using JS I'd do

// add event to the button for the demo
document.getElementById("getChecked").onclick = getChecked;

function getChecked()  {
  // get all inputs of the page
  // use node.getElementsByTagName("input") to get only child of node
  inputs = document.getElementsByTagName("input")

  checked = []
  for (let input of inputs) {
    // for each element look if it is checked
    if (input.checked) checked.push(input)
  }
  
  // here I log because can't return from event but you could return it
  console.log(checked)
}
<input id="1" name="a" type="checkbox" value="1" /> <span>a</span>
<br />
<input id="2" name="z" type="checkbox" value="2" /> <span>b</span>
<br />
<input id="3" name="e" type="checkbox" value="3" /> <span>c</span>
<br />
<input id="4" name="r" type="checkbox" value="4" /> <span>d</span>
<br />
<input id="5" name="t" type="checkbox" value="5" /> <span>e</span>
<br />
<button id="getChecked">getChecked()</button>

Edit : I'd prefer Vlad Yaremenko's answer which does the same in a more concise format

Upvotes: 0

Vlad Yaremenko
Vlad Yaremenko

Reputation: 81

You can try this

Array.from(document.querySelectorAll('input[type="checkbox"]:checked')).map(i => (i.id));

Upvotes: 2

Related Questions