如何获取已选中复选框的所有名称?

时间:2017-11-02 14:52:17

标签: javascript jquery checkbox

在我的HTML网站的末尾,我想显示所有选中复选框的名称。

例如,如果我有以下复选框:

<input type="checkbox" name="Product1" value="149"  id="checkbox_1" autocomplete="off"/>
<input type="checkbox" name="Product2" value="249"  id="checkbox_2" autocomplete="off"/>
<input type="checkbox" name="Product3" value="349"  id="checkbox_3" autocomplete="off"/>

所有被检查人员的姓名应该在同一页面上的任何位置列出,而不必按下按钮。

像这样,如果他选择2和3:

You choosed following products:
Product2
Product3

如果他没有选择什么,就不会出现任何事情。

2 个答案:

答案 0 :(得分:2)

var names = $(':checkbox:checked').map(function(){ return this.name; });
if (names.length) {
    console.log(names.get().join(','));
}

如果他们有共享课程会更好,那么你可以用

更好地选择选择器
$('.theclass').filter(':checked').map(function(){ return this.name; });

&#13;
&#13;
//demo example
$(function(){
  //get all the products
  var $allProducts = $('.product');
  //get the area to write the results to
  var $selectedProductsListing = $('#selectedProducts');
  //get the label
  var $selectedProductsLabel = $('#selectedProductsLabel');
  
  //when you click a checkbox, do the logic
  $allProducts.on('click', function(){
    //set the content of the results
    $selectedProductsListing.html(
      //only return those that are checked
      $allProducts.filter(':checked').map(function(index, checkbox){
        //return a div string with the name for display
        return '<div>'+ checkbox.name +'</div>';
      }).get().join('') //get the array of strings and join them by nothing
    );
    
    //hide the label if no checkboxes are selected
    if ($selectedProductsListing.text().trim().length) {
      $selectedProductsLabel.show();
    } else {
      $selectedProductsLabel.hide();
    }
  });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="Product1" value="149" class="product" id="checkbox_1" autocomplete="off"/>
<input type="checkbox" name="Product2" value="249" class="product" id="checkbox_2" autocomplete="off"/>
<input type="checkbox" name="Product3" value="349" class="product" id="checkbox_3" autocomplete="off"/>

<div id="selectedProductsLabel" style="display:none">Products Selected:</div>
<span id="selectedProducts"></span>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

您可以查看下面的代码段:

&#13;
&#13;
$("input").click(function(){
  var seList = $("input:checked").map(function(v){
    return (this.name);
  })
  $("#info").html(seList.join("<br>"))
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<input type="checkbox" name="Product1" value="149"  id="checkbox_1" autocomplete="off"/>
<input type="checkbox" name="Product2" value="249"  id="checkbox_2" autocomplete="off"/>
<input type="checkbox" name="Product3" value="349"  id="checkbox_3" autocomplete="off"/>
<div id="info">
</div>
&#13;
&#13;
&#13;