首页 > 解决方案 > 如何检索动态添加的复选框选定值

问题描述

我正在向我的 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 访问他们,但没有成功。

标签: javascriptjqueryhtml

解决方案


您可以使用类名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>


推荐阅读