2011-01-26 107 views
1

假设我有下面的html。怎样才能最有效地做到这一点?使用jQuery来填充选中复选框的值的范围

复选框的列表可以增长到数百,所以要保持它的小

<span class="text"></span> 
<div class="allboxes"> 
    <input type="checkbox" value="a"> 
    <input type="checkbox" value="b"> 
    <input type="checkbox" value="c"> 
    <input type="checkbox" value="d"> 
</div> 

// on click of a checkbox, span should be populated by the checked boxes 
// <span class="text">a b d</span> 

回答

2
<span class="text"></span> 
<div class="allboxes"> 
    <input type="checkbox" value="a"> 
    <input type="checkbox" value="b"> 
    <input type="checkbox" value="c"> 
    <input type="checkbox" value="d"> 
</div> 

jQuery的一部分

var n = jQuery("div.allboxes :checkbox").map(function(){ 
     return jQuery(this).val();}).get().join(" "); 
alert(n); 

工作示例here

1
jQuery('input:checked') 

并修复HTML是很重要的。属性值之间不能有逗号。

1

清理HTML:

<span class="text"></span> 
<div class="allboxes"> 
    <input type="checkbox" value="a"> 
    <input type="checkbox" value="b"> 
    <input type="checkbox" value="c"> 
    <input type="checkbox" value="d"> 
</div> 

然后你就可以做这样的事情:

$('.allboxes input').change(function() { 
    var whichSelected = []; 
    $.each($('.allboxes input:checked'), function(a,b) { 
     whichSelected.push($(b).val()); 
    }); 
    $('.text').text(whichSelected.join(' ')); 
}); 

小提琴在:http://jsfiddle.net/amirshim/sDDps/3/

1

我建议避免解析所有的复选框。使用全局数组来存储要跨度填充的值。

var globalvar = new Array(); 
function populate(obj){ 
globalvar .push(obj.value)); 
$('.text').text(globalvar.join(' ')); 
} 

做出如下的HTML。或者运行一些函数来只插入一次这些函数。

<span class="text"></span> 
<div class="allboxes"> 
    <input type="checkbox" value="a" onclick="populate(this)"> 
    <input type="checkbox" value="b" onclick="populate(this)"> 
    <input type="checkbox" value="c" onclick="populate(this)"> 
    <input type="checkbox" value="d" onclick="populate(this)"> 
</div>