How to add jQuery Chosen plugin to the checkout fields in Magento 2 so that customer can search in country list for example.
1 Answer
One way to approach this is by creating Knockout binding. Info on that can be found in this question In this approach all data changes are done by the Knockout and you need to hook into it to call $(element).trigger('chosen:updated');
to update Chosen UI.
I also needed to do some CSS styling as some times Chosen dropdown would have width:0
Another approach that was suited for my situation as I needed to update country and region dropdowns in the checkout was to use Chosen change()
function to update the UI, as data was still updated by Knockout.
So I created a function that checked if the loader is visible and once it was removed initialized Chosen with a change()
function to update the UI. Add this script to the head of checkout_index_index.xml
require([
"jquery",
"chosen.jquery"
], function ($) {
$(function () {
var initChosen = function(){
if($('#checkout-loader').length > 0) {
setTimeout(initChosen, 200);
} else {
$('select').chosen().change(function(){
$('[name="region_id"]').trigger("chosen:updated");
});
}
};
initChosen();
});
});
Also this link was useful to make Chosen work on mobile