Skip to content

Instantly share code, notes, and snippets.

@broncha
Created May 4, 2013 16:55
Show Gist options
  • Save broncha/5518071 to your computer and use it in GitHub Desktop.
Save broncha/5518071 to your computer and use it in GitHub Desktop.
Synced multiselect with jQuery multiselect and sheepit
<script type="text/javascript">
Array.prototype.removeItem = function(val){
var index = this.indexOf(val);
if(index > -1) this.splice(index,1);
}
$(document).ready(function() {
var selc = [];
var sheepItForm = $('#sheepItForm').sheepIt({
separator: '',
allowRemoveLast: false,
allowRemoveCurrent: true,
allowRemoveAll: false,
allowAdd: true,
allowAddN: false,
maxFormsCount: 10,
minFormsCount: 1,
iniFormsCount: 1,
afterAdd: function(source, newfrm){
var _f = $(newfrm),
_sel = _f.find('select.sel')[0],
_s = $(_sel);
$.each(selc, function(i, e){
_s.find('option[value="'+e+'"]')
.attr('disabled',true);
});
_s.multiselect({
header: "select country",
click: function(e, ui){
var _o = $('.sel').not(_s);
if(ui.value == 'any'){
if(ui.checked){
_s.children('option').each(function(index, opt){
//unselect selected elements
if($(opt).val() != 'any'){
//if the option was selected
if($(opt).is(':selected')){
selc.removeItem($(opt).val());
//enable unselected element in other elements
_o.children('option[value="'+$(opt).val()+'"]').attr('disabled',false);
}
$(opt).attr({'disabled':true, selected:false});
}
});
}else{
//enable available countries
_s.children('option').each(function(index, opt){
if(selc.indexOf($(opt).val()) == -1)
$(opt).attr({'disabled':false});
});
}
_s.children('option[value="any"]').attr('selected',ui.checked);
_s.multiselect('refresh');
}
_o.find('option[value="'+ui.value+'"]').attr('disabled',ui.checked);
(ui.checked) ? (selc.push(ui.value)) : (selc.removeItem(ui.value) );
//_s.multiselect('refresh');
_o.multiselect('refresh');
}
});
},
afterRemove: function(index, form){
var _f = $(form),
_sel = _f.find('select.sel')[0],
_s = $(_sel),
_o = $('.sel').not(_s);
_s.children('option').each(function(index, opt){
if($(opt).is(':selected')){
selc.removeItem($(opt).val());
//enable unselected element in other elements
_o.children('option[value="'+$(opt).val()+'"]').attr('disabled',false);
}
});
_o.multiselect('refresh');
}
});
});
</script>
@broncha
Copy link
Author

broncha commented May 4, 2013

Result

Array
(
    [countries] => Array
        (
            [0] => Array
                (
                    [0] => 2
                    [1] => 3
                )

            [1] => Array
                (
                    [0] => 4
                    [1] => 5
                )

            [2] => Array
                (
                    [0] => any
                )

            [3] => Array
                (
                    [0] => 1
                )

        )

)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment