Created
July 27, 2018 13:01
-
-
Save srghma/8de91284d4030beb0bbbd69dc524b6d7 to your computer and use it in GitHub Desktop.
chosen select multiple
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$(".chosen-select-with-add-new").chosen({ | |
no_results_text: "Click Enter or Tab to add new option", | |
width: '100%' | |
}).parent().find('.chosen-container .search-field input[type=text]').keydown(function (evt) { | |
// get keycode | |
const stroke = evt.which != null ? evt.which : evt.keyCode; | |
// If enter or tab key | |
if (stroke === 9 || stroke === 13) { | |
const target = $(evt.target); | |
// get the list of current options | |
const chosenList = target.parents('.chosen-container').find('.chosen-choices li.search-choice > span').map(function () { return $(this).text(); }).get(); | |
// get the list of matches from the existing drop-down | |
const matchList = target.parents('.chosen-container').find('.chosen-results li').map(function () { return $(this).text(); }).get(); | |
// highlighted option | |
const highlightedList = target.parents('.chosen-container').find('.chosen-results li.highlighted').map(function () { return $(this).text(); }).get(); | |
// Get the value which the user has typed in | |
const newString = $.trim(target.val()); | |
// if the option does not exists, and the text doesn't exactly match an existing option, and there is not an option highlighted in the list | |
if ($.inArray(newString, matchList) < 0 && $.inArray(newString,chosenList) < 0 && highlightedList.length == 0) { | |
// Create a new option and add it to the list (but don't make it selected) | |
const newOption = '<option value="' + newString + '" selected="selected">' + newString + '</option>'; | |
const choiceSelect = target.parents('.chosen-container').siblings('.chosen-select-with-add-new'); | |
choiceSelect.append(newOption); | |
// trigger the update event | |
choiceSelect.trigger("chosen:updated"); | |
// tell chosen to close the list box | |
choiceSelect.trigger("chosen:close"); | |
return true; | |
} | |
// otherwise, just let the event bubble up | |
return true; | |
} | |
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
.tag-list | |
label.control-label.h5 Tag list | |
= select_tag :tag_list, options_for_select(ActsAsTaggableOn::Tag.order('taggings_count desc').pluck(:name), @publication.tags.map(&:name)), multiple: true, data: { placeholder: 'north, east, south, west' }, class: 'chosen-select-with-add-new' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment