about uscontact

How to add a new options by user to Select2 dropdown

Category:
Author: zemna
Date: April 17, 2021
Share this:

If you want to give user can add new options to select tag in runtime, you can use Select2 jQuery library to do it.

Final result is like this:

Select2 Dropdown{: .img-responsive }

1. Enable tags option

$('select').select2({
tags: true
});

2. Handle createTag function to add extra properties

$('select').select2({
tags: true,
createTag: function (params) {
var term = $.trim(params.term);

if (term === '') {
return null;
}

return {
id: term,
text: term,
newTag: true // add additional perameters
}
}
});

3. Update templateResult function to display "(new)" text inside of item

$('select').select2({
tags: true,
createTag: function (params) {
var term = $.trim(params.term);

if (term === '') {
return null;
}

return {
id: term,
text: term,
newTag: true // add additional perameters
}
},
templateResult: function(data) {
var $result = $("");

$result.text(data.text);

if (data.newTag) {
$result.append(" (new)");
}

return $result;
}
});

References

Share this:

Leave a Reply

Your email address will not be published.

ZEMNA.NET

Professional software development agency estalished in Indonesia. We offers website setup, web application development, fulfillment service, and etc.
Follow us
Follow us to get latest news and tutorials.
2022 - Copyright, All Rights Reserved, Made by ZEMNA.NET with ❤️
magnifiercrossmenu