I am using the chosen plugin.
Adding this to my document does not enable me to type into the text field and add a new item to the list.
$(document).ready(function (){
$(".chosen-select").trigger("chosen:updated");
});
This will allow some hard coded text to be added to the list:
$(document).ready(function (){
$('.chosen-select').chosen();
$('.addsomething').click(function (){
$(".chosen-select").prepend("<option>Utopia</option>");
$(".chosen-select").trigger("chosen:updated");
});
});
What I would like to see happen is I would like to be able to add text to the text field, hit return and have my entry be added if I have not chosen it. It does not need to be permanently added to the options list.
Not sure if it can be done in an easier way, but this works just fine. The comments from the code explain each step:
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");
}
});
Here's a working example: http://jsfiddle.net/jHvmg/436/
I modified the answer from Bogdan to work with chosen 1.2.0 as well as with all types of chosen selects:
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");
}
});
A simple alternative is to use select2, which has tags build in: https://select2.github.io/examples.html#tags
$(".js-example-tags").select2({
tags: true
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With