I have multiple drop down lists (select & option) that are populated by data from the server. They all have the same options, but I need the use to be able to select every option only once - it can appear as selected only on one list.
This is the HTML of a single list - simple select & options list:
<div class="social-option">
<select name="hex_theme_options[social-service-1]">
<option selected="selected" value="0"></option>
<option value="facebook">facebook</option>
<option value="twitter">twitter</option>
<option value="linkedin">linkedin</option>
<option value="e-mail">e-mail</option>
<option value="phone">phone</option>
<option value="instagram">instagram</option>
<option value="flickr">flickr</option>
<option value="dribbble">dribbble</option>
<option value="skype">skype</option>
<option value="picasa">picasa</option>
<option value="google-plus">google-plus</option>
<option value="forrst">forrst</option>
</select>
</div>
And this is the JS code for managing them the way I described. It works, but it looks pretty ugly to me, and I'd like to improve it's structure. Any suggestions are welcome.
(function($){
$(document).ready(function() {
var siblings = {
lock: function (newSelected){
var selectedSiblings = $('.social-option select').find("option[value=" + newSelected.val() + "]");
selectedSiblings.not(newSelected).attr('disabled', 'disabled');
},
unlock: function (oldSelected){
var selectedSiblings = $('.social-option select').find("option[value=" + oldSelected.val() + "]");
selectedSiblings.removeAttr('disabled');
},
unlockZero: function (){
$('.social-option select').find("option[value='0']").removeAttr('disabled');
}
};
function checkSiblings(oldSelected, newSelected) {
if (oldSelected === '0') {
siblings.lock(newSelected);
} else if (newSelected === '0') {
siblings.unlock(oldSelected);
} else {
siblings.unlock(oldSelected);
siblings.lock(newSelected);
}
}
$('.social-option select').each(function() {
siblings.lock($('option:selected', this));
siblings.unlockZero();
});
$('.social-option select').on('focus', function () {
var oldSelected = $('option:selected', this);
$('.social-option select').on('change', function () {
var newSelected = $('option:selected', this);
checkSiblings(oldSelected, newSelected);
});
});
});
})(jQuery);