2011-01-26 66 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>