Assume i have the html below. What will be the way to do it the most efficiently?
The list of checkboxes can grow to many hundreds, so it is important to keep it small
<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>
<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 part
var n = jQuery("div.allboxes :checkbox").map(function(){
return jQuery(this).val();}).get().join(" ");
alert(n);
working example here
jQuery('input:checked')
And fix the HTML. You can't have commas between attribute values.
Clean up the 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>
And then you can do something like this:
$('.allboxes input').change(function() {
var whichSelected = [];
$.each($('.allboxes input:checked'), function(a,b) {
whichSelected.push($(b).val());
});
$('.text').text(whichSelected.join(' '));
});
Fiddle at: http://jsfiddle.net/amirshim/sDDps/3/
I would suggest avoid parsing all the checkboxes. Use a global array to store the values to be populated in span.
var globalvar = new Array();
function populate(obj){
globalvar .push( obj.value));
$('.text').text(globalvar.join(' '));
}
make the html as below. Or run some function to insert those functions only once.
<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>
精彩评论