javascript - 如何检索动态添加的复选框选定值
问题描述
我正在向我的 html 页面动态添加复选框。用户进行选择时如何检索值。
var sources = source_names_list;
$.each(sources, function(index,value) {
// var checkbox1 = "<label for="+test+"<input type='checkbox' id=\"+test+\" value=\"+test+\" name=\"+test+\"></label>"
// var checkbox="<label for="+value+">"+value+"<input type='checkbox' id="+value+" value="+value+" name="+value+"></label></br>"
var checkbox1 = "<p><label><input type=\"checkbox\" id="+value+" class=\"filled-in\"/><span>" + value + "</span></label></p>"
$("#sources").append($(checkbox1));
});
我尝试使用他们的 id 访问他们,但没有成功。
解决方案
您可以使用类名filled-in
作为选择器来获取值。您还需要为value
每个生成的复选框添加一个。
// Sources
var source_name_list = ['news' , 'info', 'article', 'newyork,items'];
// Create all the checkboxes (adding a value to each one)
$.each(source_name_list, function(index,value) {
var checkbox = '<p><label><input type="checkbox" id="'+value+'" value="' + value + '" class="filled-in" /><span>' + value + '</span></label></p>';
$("#sources").append($(checkbox));
});
// "get selected" button
$('#get').click(function() {
// Create an array for the values
var values = [];
// Select all checkboxes by class name, and use the jQuery :checked special selector
$('.filled-in:checked').each(function() {
// Adds the value to the values array
values.push($(this).val());
});
// Log all values
console.log(values);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="sources"></div>
<a id="get">Get selected</a>
推荐阅读
- powershell - 对于包含哈希 (#) 的文件夹名称,Add-PnPFolder 失败
- javascript - 渲染过程中 IPCRenderer 的电子错误
- python - 如何创建一个数据框,其中包含一个键下的二维列表?
- python - 如何从大文件名数组中测试文件是否存在,如果文件名不以一致的方式存在,如何从数组中删除文件名?
- python - 无法将数据框转换为 stata 格式
- javascript - javascript 验证 lang, lat 为 dmc 格式
- qt - QApplication 从分段错误中恢复
- php - 如何获取artifactsrequests 表的ID,而不是我加入的表的ID
- python - 如何找到一维数组/向量的自相关矩阵
- linux - 安装后正在替换 linux 中的 npm install 文件夹