I have integrated 4.0.8 version in my project and wants to achieve two things.
-
When drop-down is appearing and user click on an option user will be redirected to the URL given in extra attribute of option, i made the changes in “templateSelection” and it is working correctly.
-
My second option is if users enter some text and press enter key after/before appearing drop-down list, there is form on the page which should be submitted and its default behavior (redirected to other page) should stopped. This working correctly when user hit enter key before options appear but when option is available it is always picking the first option and user is redirected to other page and my form is not submitted. Here is code i used:
jQuery('#text_Search').select2({ ajax: { url: 'index.php', dataType: 'json', method:'POST', delay: 1000, data: function (params) { var queryParameters = { searchTerm: params.term } return queryParameters; }, processResults: function (data) { var resultArray = []; jQuery.each(data, function(i, v) { let url = 'someurl'; resultArray.push({id:v.id,name:v.name,level:1,url:url}); }); return { results: resultArray }; }, cache: true }, placeholder: 'Search...', minimumInputLength: 2, templateResult: formatResult, allowClear: true, templateSelection: formatResultSelection }); function formatResult (result) { if (result.loading) { return result.text; } return "formated result"; } function formatResultSelection (data) { if(data.url) { var location = data.url; if(location && location!='#') window.location = location; } return data.name || data.text; } jQuery("#text_Search").on("keydown", function (e) { if (e.keyCode == 13) { e.preventDefault(); let searchTxt = jQuery(".select2-search__field").val(); jQuery("#search").val(searchTxt); jQuery("#Form").submit(); } });