Добавление текста, отличного от выбранных параметров текста, к выбору с помощью выбранного вами модуля
Я использую выбранный плагин.
Добавление этого в мой документ не позволяет мне вводить текстовое поле и добавлять в него новый элемент.
$(document).ready(function (){
$(".chosen-select").trigger("chosen:updated");
});
Это позволит добавить в список некоторые жестко закодированные тексты:
$(document).ready(function (){
$('.chosen-select').chosen();
$('.addsomething').click(function (){
$(".chosen-select").prepend("<option>Utopia</option>");
$(".chosen-select").trigger("chosen:updated");
});
});
То, что я хотел бы видеть, это то, что я хотел бы добавить текст в текстовое поле, нажать return и добавить свою запись, если я ее не выбрал. Его необязательно добавлять в список опций.
Ответы
Ответ 1
Не уверен, что это можно сделать более простым способом, но это работает отлично. Комментарии из кода объясняют каждый шаг:
var select, chosen;
// Cache the select element as we'll be using it a few times
select = $(".chosen-select");
// Init the chosen plugin
select.chosen({ no_results_text: 'Press Enter to add new entry:' });
// Get the chosen object
chosen = select.data('chosen');
// Bind the keyup event to the search box input
chosen.dropdown.find('input').on('keyup', function(e)
{
// If we hit Enter and the results list is empty (no matches) add the option
if (e.which === 13 && chosen.dropdown.find('li.no-results').length > 0)
{
var option = $("<option>").val(this.value).text(this.value);
// Add the new option
select.prepend(option);
// Automatically select it
select.find(option).prop('selected', true);
// Trigger the update
select.trigger("chosen:updated");
}
});
Вот рабочий пример: http://jsfiddle.net/jHvmg/436/
Ответ 2
Я изменил ответ от Богдана, чтобы работать с выбранным 1.2.0, а также со всеми типами выбранных select:
var select, chosen;
// cache the select element as we'll be using it a few times
select = $(".chosen-select");
// init the chosen plugin
select.chosen();
// get the chosen object (any type, single or multiple)
chosen = $('.chosen-container');
// chosen = $('.chosen-select-single');
// chosen = $('.chosen-container-multi');
// Bind the keyup event to the search box input
chosen.find('input').keyup( function(e)
{
// if we hit Enter and the results list is empty (no matches) add the option
if (e.which === 13 && chosen.find('li.no-results').length > 0)
{
var option = $("<option>").val(this.value).text(this.value);
// add the new option
select.prepend(option);
// automatically select it
select.find(option).prop('selected', true);
// trigger the update
select.trigger("chosen:updated");
}
});
Ответ 3
Простой альтернативой является использование select2, в котором встроены теги:
https://select2.github.io/examples.html#tags
$(".js-example-tags").select2({
tags: true
})
Ответ 4
Здесь есть статья о том, как добавить новые значения в выбранный список выбора:
https://boundlessjourney.wordpress.com/2014/06/12/adding-new-values-to-chosen-plugin/
В основном вы редактируете файл selected.jquery.js и выполняете поиск case 13:
и заменяете код в корпусе коммутатора
case 13:
evt.preventDefault();
if (this.results_showing) {
if (!this.is_multiple || this.result_highlight) {
return this.result_select(evt);
}
$(this.form_field).append('<option>' + $(evt.target).val() + '</option>');
$(this.form_field).trigger('chosen:updated');
this.result_highlight = this.search_results.find('li.active-result').last();
return this.result_select(evt);
}
break;
Это для мультиселектов, но в моем случае я хотел иметь возможность добавить одну опцию. Я нашел ответ в комментариях, но у него отсутствовал код, и я добавляю возможность заглавной буквы каждого слова.
Это можно сделать, заменив код в корпусе коммутатора:
case 13:
evt.preventDefault();
if (this.results_showing) {
if (this.result_highlight) {
return this.result_select(evt);
}
$(this.form_field).append('<option>' + ($(evt.target).val()).replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();}) + '</option>');
$(this.form_field).trigger('chosen:updated');
this.result_highlight = this.search_results.find('li.active-result').last();
return this.result_select(evt);
}
break;
Возможно, код можно отредактировать, чтобы он мог принимать как мультиселекты, так и одиночные
Ответ 5
$('.choose').chosen();
$('.choose').on('chosen:no_results',function(evt, params)
{
var value = params.chosen.search_results.find('span').text();
$('.choose').append(new Option(value, value,true).outerHTML);
$('.choose').trigger("chosen:updated");
});