2012-03-13 52 views
0

我需要获取当前使用jquery检查的所有复选框的值,我想我会把它全部放在一个数组中,但我遇到了麻烦那。任何人都可以指出我的写作方向。如何获取与jquery相同的类的多个复选框的值

这是我目前使用的。我试图将当前选中的所有值发送给我拥有的div。

function cityPopulate() { 


     var arr44 = new Array(); 
     var cityNames22 = $("input[name=city_select[]]:checked").each(function(){arr44.push(this.value);}); 



     $("#city_pop").append(cityNames22.val()); 
    } 

     When I try the code above, it just gives me the value of the first checkbox I check only. Not all of the rest. 
+0

你可以发布你到目前为止的代码吗? – 2012-03-13 21:12:13

+0

可能重复的问题:http://stackoverflow.com/questions/786142/how-to-retrieve-checkboxes-values-in-jquery – 2012-03-13 21:13:59

回答

2

没有看到你有我在你确切的架构猜测的代码,但使用map()在你的复选框与类指定要创建数组应该工作,试试这个:

var checkboxValues = $('.myCheckbox:checked').map(function() { 
    return $(this).val(); 
}).get(); 

checkboxValues随后将包含数组中所有的值选中的复选框。

+0

这实际上工作的原因,我看到在JavaScript错误它给我所有的价值现在,但我将如何显示这个数组。现在它不会显示,它给我的错误“object has no method val” – 2012-03-13 21:22:41

+0

要显示一个数组作为字符串,你需要'join()'它 - '$(“#city_pop”)。append(checkboxValues 。加入( ''));' – 2012-03-14 08:49:45

0

根据已分配给您的复选框的类,它会是这个样子:

var values = []; 

$('.checkboxclass').each(function(){ 
    var $this = $(this); 
    if ($this.is(':checked')) { 
    values.push($this.val()); 
    } 
}); 
相关问题