How to Select a Result from the Select2 Search Results

Unable to select a result from the select2 search results

You are missing id attribute for result data. if it has not, it makes option "unselectable".

Example:

            $('#e7').select2({
id: function(e) { return e.productName; },
});

How do I get a search query in select2?

As mentioned in the comment on the question you are currently using an older version of Select2, presumed to be Select v3.5.2 or similar. Versions prior to v4 have different options, namely formatResult must be passed to format a result as used in your question. The documentation on this can be found here around halfway down the page.

The documentation shows that the arguments passed to a formatResult function are:

formatResult(object, container, query)

Where the third argument query is defined as The query object used to request this set of results.. This query object contains the search as the term property. Therefore the below prints the entered search query.

formatResult: function(object, container, query) {
var term = query.term;
console.log('search term is', term);
}

This is incorporated into an example at https://jsfiddle.net/j89q15d6/ and also in the page below. For demonstration purposes the example appends the search term to the text of the result in brackets.

// Template function which adds CSS flag and displays country name
function flagTemplate(object, container, query) {
let term = "";

// Check the search term, if one is found set term variable to be included in result
if (query.term) {
// search term is set
term = " (" + query.term + ")";
}

// Append the search term to the result, just for testing
return $("<span class='flag-icon flag-icon-" + object.id + " '></span><span class='flag-text'>" + object.text + term + "</span>");
}

// Generate the correct URL
function generateUrl(term) {
if (term) {
return "https://restcountries.com/v3.1/name/" + term;
} else {
return "https://restcountries.com/v3.1/all";
}
}

// Initialise select2
var $selectField = $('#countrySelect');
$selectField.select2({
width: "element",
// Set template for results and selection
formatResult: flagTemplate,
formatSelection: flagTemplate,
// Set placeholder text
placeholder: 'Select country...',
// Load country list from https://restcountries.com
ajax: {
url: generateUrl,
delay: 250,
dataType: "json",
results: function(data) {
return {
results: data
.map(x => ({
id: x.cca2.toLowerCase(),
text: x.name.official
}))
.sort((a, b) => ('' + a.text).localeCompare(b.text))
};
}
}
});
#countrySelect {
width: 300px;
}

.flag-text {
margin-left: 10px;
}
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.2/select2.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.2/select2.js"></script>

<!-- Load flags using library https://github.com/lipis/flag-icons -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/flag-icon-css/4.1.5/css/flag-icons.min.css" rel="stylesheet"/>

<div>Select v3.5.2 Example</div>
<input type="hidden" id="countrySelect">

Select2, select a text if no results available

Try setting tags:true when initializing the select box, that will temporarily add the typed value to the list

select2 ajax shows results but can't select

Its a quick hack. Not sure how you could get along with select2 documentaion. But the following code worked with me in my localhost.

$(document).ready(function(){
$.get("json/select.json",function(data){ //specify your url for json call inside the quotes.
for(var i = 0; i < data.length; i++){
data[i]={id:i,text:data[i].text}
}
$(".js-data-example-ajax").select2({
minimumInputLength: 2,
multiple:true,
delay: 250,
data: data
})

});
}

Select2 - Ajax search - remember last results

I did read your post once again.
I misunderstood you last time.

The solution is here.

   $(document).ready(function () {
$('#select').select2({
// this part is responsible for data caching
dataCache: [],
query: function (q) {
var obj = this,
key = q.term,
dataCache = obj.dataCache[key];

//checking is result in cache
if (dataCache) {
q.callback({results: dataCache.results});
} else {
$.ajax({
url: 'ajax.php',
data: {q: q.term},
dataType: 'json',
type: 'POST',
success: function (data) {
//copy data to 'cache'
obj.dataCache[key] = data;
q.callback({results: data.results});
}
})
}
},
placeholder: 'Search something',
width: '333',
minimumInputLength: 3,
});
// this part is responsible for setting last search when select2 is opening
var last_search = '';
$('#select').on('select2-open', function () {
if (last_search) {
$('.select2-search').find('input').val(last_search).trigger('paste');
}
});
$('#select').on('select2-loaded', function () {
last_search = $('.select2-search').find('input').val();
});
});

how to retain Select2 results after select?

Sounds like you want to persist a query from one search to the next. You might want to check out the nextSearchTerm property.

To display the current value in the next search,

function displayCurrentValue(selectedObject, currentSearchTerm) {
return currentSearchTerm;
}

$("#e1").select2({
nextSearchTerm: displayCurrentValue
});


Related Topics



Leave a reply



Submit