Перемещение и сортировка checkbox'ов
by krivega
HTML
<form>
<div id='form1'>
<input type='checkbox' id='check1'><label for='check1'>Петров</label>
<input type='checkbox' id='check2'><label for='check2'>Иванов</label>
<input type='checkbox' id='check3'><label for='check3'>Сидоров</label>
<input type='checkbox' id='check4'><label for='check4'>Авдофий</label>
</div>
<div id='form2'></div>
</form>
CSS
#form1, #form2{
display:block;
overflow-y:scroll;
float:left;
padding:5px 7px 10px;
margin:20px 10px 0;
min-height:150px;
min-width:120px;
}
input[type='checkbox'] {
float: left;
clear: both;
margin:2px 5px 3px 0;
height:22px;
cursor:pointer;
}
label{
float: left;
margin:2px 0 3px;
line-height:22px;
cursor:pointer;
}
JavaScript
$(document).ready(function() {
function sortContent(container, sortInput, sortlabel){
var elms = [];
$(sortInput).each(function() {
var pair = {
inputTag: $(this),
labelTag: $(this).next("label")
};
elms.push(pair);
});
$(sortInput).detach();
$(sortlabel).detach();
elms.sort(function(a, b) {
return a.labelTag.text() > b.labelTag.text();
});
$.each(elms , function(){
$(container).append(this.inputTag).append(this.labelTag);
});
}
sortContent('#form1', '#form1 input[type=checkbox]', '#form1 label');
$('#form1').on('change', 'input[type=checkbox]', function () {
var $this = $(this),
thisId = $this.attr('id'),
thisLabel = $('#form1').find('label[for="' + thisId + '"]');
if ($this.is(':checked')) {
$this.appendTo('#form2');
thisLabel.appendTo('#form2');
}
sortContent('#form2', '#form2 input[type=checkbox]', '#form2 label');
});
$('#form2').on('change', 'input', function () {
var $this = $(this),
thisId = $this.attr('id'),
thisLabel = $('#form2').find('label[for="' + thisId + '"]');
if (!$this.is(':checked')) {
$this.appendTo('#form1');
thisLabel.appendTo('#form1');
}
sortContent('#form1', '#form1 input[type=checkbox]', '#form1 label');
});
});