如何检索动态添加的复选框选择值

时间:2018-06-13 18:33:42

标签: javascript jquery html5

我正在动态添加复选框到我的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访问它们,但它没有用。

1 个答案:

答案 0 :(得分:1)

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