Skip to content

Instantly share code, notes, and snippets.

@joelworsham
Created November 25, 2014 16:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joelworsham/0f650c68a169935689bc to your computer and use it in GitHub Desktop.
Save joelworsham/0f650c68a169935689bc to your computer and use it in GitHub Desktop.
Chosen Custom Input
// Apply Chosen
var $chosen = $('.chosen'),
container = '.container-class';
$chosen.chosen();
// Extend functionality to allow custom text input (if enabled on input)
if ($chosen.hasClass('allow-custom-input')) {
// When hiding the dropdown (submitting the field), use our custom input
$chosen.on('chosen:hiding_dropdown', function () {
var name = $(this).attr('name'),
$self = $(this),
$container = $(this).closest(container_class),
custom_val = $container.find('.chosen-search input[type="text"]').val(),
$custom_input = $container.find('.chosen-custom-input'),
$placeholder = $container.find('.chosen-container .chosen-single');
// An existing value has been selected manually or there was no input
if (!custom_val.length) {
if ($custom_input.length) {
$custom_input.remove();
}
return;
}
// See if value exists in selectbox, and if it does, set chosen to that value
var exists = false;
$(this).find('option').each(function () {
if ($(this).val() == custom_val) {
$self.val(custom_val).trigger('chosen:updated');
exists = true;
return false;
}
});
if (exists) {
return;
}
if (!$custom_input.length) {
$container.append('<input type="hidden" class="chosen-custom-input" name="' + name + '" />');
$custom_input = $container.find('.chosen-custom-input');
}
$custom_input.val(custom_val);
$placeholder.removeClass('chosen-default');
$placeholder.find('> span').html(custom_val);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment