I have this long list of checkboxes with specific labels that look something like this:
<input type='checkbox' name='check[]' id='159' value='159' />
<label for='159'>Person 1</label>
<input type='checkbox' name='check[]' id='160' value='160' />
<label for='160'>Person 2</label>
And below this form I have six div’s like so:
<div id="member1"></div>
<div id="member2"></div>
<div id="member3"></div>
<div id="member4"></div>
<div id="member5"></div>
<div id="member6"></div>
I have this JS function so that when I click on a checkbox, it’s label is inserted into the first div. Here’s what it looks like:
$(function(){
$('input:checkbox').click(function(){
var id = $(this).attr('id');
if($(this).is(':checked')){
$('#member1').text($('label[for="'+ id +'"]').text());
}
else{
$('#member1').text('');
}
});
});
So one problem is the function currently has to specify which div to put it into (#member1). It’s supposed to work that when the first div is “full”, the next checkbox will insert its label into the second div, and when that one is full, the third checkbox will insert its label into the third div, etc.
The other issue is if a checkbox becomes unchecked, its label should be removed from its div and the labels in the divs below it should move up. Anyone know if that’s possible? I’ll accept help for either problem!
Caveat: I would do this completely differently.
But using your current structure: Live copy | source (using valid
ids)Minimum changes I would make:
#memberXdivs in a container so we don’t have to do theid^=search.idvalues on the#memberXdivs at all.#memberdivs at all. This would simplify the code markedly.Example: Live copy | source
HTML:
Just replace the
#membersXdivs with<div id="members"></div>".JavaScript:
You can simplify even more by moving the checkbox input the
labels (which also means you can do away with theforattribute): Live copy | sourceHTML:
JavaScript: