获取已选中的动态生成复选框的ID

问题描述 投票:2回答:4

假设我有x个复选框:

<input type="checkbox" id="ams" value="False">
<input type="checkbox" id="lon" value="False">
<input type="checkbox" id="ber" value="False">
<input type="checkbox" id="par" value="False">

我想按一下按钮:

<button type="submit_cities" id="submit_cities">Print selected cities</button>

打印所选复选框的ID。有办法解决吗?谢谢!

javascript jquery html
4个回答
1
投票

使用按钮的id添加单击处理程序,然后遍历所选输入:

$("#submit_cities").click(function() {
  $('input:checked').each((_, elm) => console.log(elm.id));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" id="ams" value="False">
<input type="checkbox" id="lon" value="False">
<input type="checkbox" id="ber" value="False">
<input type="checkbox" id="par" value="False">
<button type="submit_cities" id="submit_cities">Print selected cities</button>

2
投票

看看我的解决方案如下。

const checkboxes = [ ...document.querySelectorAll('input[type="checkbox"]') ]
const submitButton = document.querySelector('#submit_cities')

const getCheckedIDs = () => 
  checkboxes
    .filter(checkbox => checkbox.checked)
    .map(checkbox => checkbox.getAttribute('id'))

submitButton.onclick = () => {
  console.log(getCheckedIDs())
}
<input type="checkbox" id="ams" value="False">
<input type="checkbox" id="lon" value="False">
<input type="checkbox" id="ber" value="False">
<input type="checkbox" id="par" value="False">
<button type="submit_cities" id="submit_cities">Print selected cities</button>

2
投票

无效的按钮类型。随着type="button"的变化。你可以使用Jquery#filterJquery#map.get() api

并使用.on()专门用于动态附加元素

$(document).on('click', '#submit_cities', function() {
  var $arr = $('input[type="checkbox"]').filter((a, b) => $(b).is(':checked')).map((a, b) => $(b).attr('id')).get()
  console.log($arr)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" id="ams" value="False">
<input type="checkbox" id="lon" value="False">
<input type="checkbox" id="ber" value="False">
<input type="checkbox" id="par" value="False"> And I'd like upon pressing a button:

<button type="button" id="submit_cities">Print selected cities</button>

0
投票

这是我的解决方案:

function select()
{
   var results=$("input:checkbox:checked");
   for (i=0;i< results.length;i++)
   {
     alert(results[i].id);
   }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" id="ams" value="False">
<input type="checkbox" id="lon" value="False">
<input type="checkbox" id="ber" value="False">
<input type="checkbox" id="par" value="False">

<button onclick="select()">
Go
</button>
© www.soinside.com 2019 - 2024. All rights reserved.