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

假设我有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 。 有办法解决吗? 谢谢!

时间:

使用按钮的id添加一个 clickhandler,然后按选定的输入循环:


$("#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>

看看我的解决方案如下。


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>

button. so/change _ change/_ api/api _ api _ api/api _ api/api _ api/api 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>

以下是我的解决方案:


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