[英]Javascript: How to get values from checkboxes that are created “dynamically”
So i am creating/rendering checkboxes dynamically depending on the records in my database. 因此,我将根据数据库中的记录动态创建/呈现复选框。 This is currently the way for "displaying" those Checkboxes:
当前,这是“显示”这些复选框的方法:
function formatBranch(branch) {
return (
"<p>\n" +
" <label>\n" +
" <input id=" + branch['name'] + " type=\"checkbox\" class=\"filled-in libraryCheckbox\">\n" +
" <span>" + branch['name'] + "</span>\n" +
" </label>\n" +
"</p>"
);
}
I now need to check which checboxes are checked and retrieve that/those specific checboxes as I am going to use them to filter out a search. 现在,我需要检查选中了哪些复选框,并检索那些/这些特定的复选框,因为我将使用它们来过滤搜索。 Any ideas for how i can achieve this?
关于如何实现这一目标的任何想法?
Thanks for any help :) 谢谢你的帮助 :)
To get all checkboxes values with pure js: 要使用纯js获取所有复选框值:
let chks = document.getElementsByTagName("input");
for(var i = 0; i < chks.length; i++) {
if(chks[i].type == "checkbox") {
if (chks[i].checked) {
// the checkbox is clicked
} else {
// checkbox is not clicked
}
}
}
You can use it to build an array of filters or something like this 您可以使用它来构建过滤器数组或类似的东西
If you want to act on click, do something like this: 如果您想点击操作,请执行以下操作:
let chks = document.getElementsByTagName("input");
for(var i = 0; i < chks.length; i++) {
if(chks[i].type == "checkbox") {
chks[i].addEventListener('change', function(e){
if (e.target.checked) {
// clicked
} else {
// not clicked
}
});
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.