获取所有选中的复选框,并在数组中添加其名称和值

时间:2014-02-18 09:41:37

标签: javascript jquery checkbox

我有大表格主要是下拉列表和复选框。复选框是动态创建的,因此在创建它之前我不知道它们的ID。我使用drop down onChange事件来动态创建它们。

如何循环显示表单并获取所有选中的复选框,即他们的ID和值?我只需要对选中的复选框执行此操作。所有复选框共享相同的名称,即:categoriesfilters []。目前我在复选框上点击事件,调用javascript函数。

以下是代码:

function update_number_of_adds_found(field_dropdown,selected_value) {
                selected_value="";

               var addtypeid = $("#addtypeid").val();

               // trying to store the values of the checkboxes

                $(this).find("input[type=checkbox]:checked").each( 
                  function() { 
                   var id = $(this).attr('id');
                   var value = $(this).val(); // or maybe attr('value');
                   // the data is stored, do whatever you want with it.
                    alert(value);
                  } 
                );

               var selected_value = {
                                        addtypeid: addtypeid,
                                        // need to add the ids and the values here as well
                                    };



                 var url = "<?php echo site_url('search/findNumberOfAdds'); ?>";
        $.post(url, selected_value, function(r){
            if(r) {

                $('#totalNumOfAdds').empty();
                $("#totalNumOfAdds").append(r.result); 
            } else { 
               // alert(selected_value);
            }
        }, 'json')



            }

问候,约翰

4 个答案:

答案 0 :(得分:1)

试试这个:

var categories = [];

$("input[name='categoriesfilters[]']:checked").each( 
  function() { 
      var id = $(this).attr("id");
      var value = $(this).val();
      categories[categories.length] = {id : value};
  } 
);

console.log(categories);

$.post(url, categories, function(r){

...

答案 1 :(得分:0)

试试这个:

$('form').submit(function(){
$(this).find("input[type=checkbox]:checked").each( 
  function() { 
   var id = $(this).attr('id');
   var value = $(this).val(); // or maybe attr('value');
   // the data is stored, do whatever you want with it.
  } 
);
});

我想你想在表格提交上检查一下。

答案 2 :(得分:0)

var arr = [];
$('input[name^="categoriesfilters"]:checked').each(function() {
    var obj = {
        id: $(this).attr('id');
        value: $(this).val();
    };
    arr.push(obj);        
});
console.log(arr); // show us the array of objects

答案 3 :(得分:0)

您想使用Jquery吗?

为每个复选框添加一个类,即“class_chk”;

$(function(){
     $('.class_chk').each(function(){
         if($(this).is(':checked')){
                var id = $(this).attr('id');
                var val = $(this).val();
                alert("id = "+id+"---- value ="+val);
         }  
   });
});

通过上述方式,您可以获取所有选中的复选框ID和值。

谢谢..