I have to fix a glitch with this code someone wrote but I’m not skilled enough at jQuery to figure it out myself. Maybe someone here can help me. First I’ll try explain what is supposed to happen…
Basically the idea is that you have a list of people with checkboxes next to their names. And below them you have six available slots (empty divs). When you check a box, the person’s name is inserted into one of the empty divs. Up to a maximum of six obviously.
The tricky part is if you uncheck a box you checked, the name should disappear from the slot, and all the names below it should move up one slot to fill the gap. This is where the glitch is happening. If you uncheck a box twice in a row, the second time nothing happens, or the third, etc…
This is the jQuery function we have so far:
$(function(){
$('input:checkbox').click(function(){
var $cb = $(this),
id = this.id, // No need for `attr`
member,
prev;
if(this.checked){ // No need for `attr`
$("div[id^=member]").each(function() {
if (!this.firstChild) {
// It's empty, use it
$(this).text($('label[for="'+ id +'"]').text()).attr("data-contents", id);
return false; // Done
}
});
}
else {
member = $('div[data-contents="' + id + '"]');
if (member[0]) {
member.empty('').removeAttr('data-contents');
prev = member[0];
member.nextAll().each(function() {
if (!this.firstChild) {
return false; // Done
}
prev.appendChild(this.firstChild);
prev = this;
});
}
}
});
});
Here’s an example of one of the checkboxes and some of the divs:
<input type='checkbox' name='check[]' id='155' value='155'/>
<label for='155'>John Doe</label>
<input type='checkbox' name='check[]' id='156' value='156'/>
<label for='156'>John Smith</label>
and
<div id="member1" class="member"></div>
<div id="member2" class="member"></div>
You have some strangely un-jQuery-like behavior in your script, but we’ll let that go for now.
The problem, as I saw it in my browser’s DOM inspector, is that when you unchecked a box it might reassign the contents of the second DIV to the first one, but it wouldn’t reassign the
data-contentsattribute at the same time.Modified code:
http://jsfiddle.net/q6Vg9/