如何从foreach循环中获取已选中复选框的ID

时间:2018-08-20 14:31:30

标签: javascript asp.net-mvc

我有一个foreach循环,为Db中表中的每个记录创建一个复选框,如下所示:

@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 />
}

我的问题是,我是否有办法检索所有选中复选框的ID?

2 个答案:

答案 0 :(得分:2)

您可以尝试

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

答案 1 :(得分:0)

我会用JS

// 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>

编辑:我希望Vlad Yaremenko的答案以更简洁的格式进行处理