5

I have jquery chosen dropdown that works fine for my need. The only requirement I have is can we get the matched search results (options that starts with search key) at the top.

If I have 3 options Foo, Boo, ooo then search for oo. Getting the results in alphabetical order like Boo, Foo, ooo. But, can we get a result like ooo, Boo, Foo.

$('.chosen-select').chosen({
    width: "100%",
    search_contains: true
});

I'm not sure if the plugin has any support for this. Please suggest.

ankitkanojia
  • 3,072
  • 4
  • 22
  • 35
Spring
  • 648
  • 1
  • 7
  • 20
  • Does this answer your question? [Chosen jQuery plugin : get multiple select values in the order they were clicked](https://stackoverflow.com/questions/21659224/chosen-jquery-plugin-get-multiple-select-values-in-the-order-they-were-clicked) – Roy Bogado Jan 23 '20 at 09:33
  • Thanks @Roy for the response. I think the plugin they providing there supporting the selection in order. But, I want the search results to be ordered in way that first letter matches are at the top then the rest of the options. – Spring Jan 23 '20 at 09:49

1 Answers1

0

You can write your custom logic like below. I have added fiddle for same in comments.

<div id = "results"></div>


$( document ).ready(function() {
    var chosenValues = ["Foo", "Boo", "Ooo"];
    var sortedData = checkStartsWith(chosenValues, 'oo');    
        $("#results").text(sortedData)
});
function checkStartsWith(chosenValues, searchTerm) {
    var matchedData = [];
    var unMatchedData = [];
    for (var i = 0; i < chosenValues.length; i++) {
        // This condition will check if searchTerm is at the beginning of data
        if (chosenValues[i].toLowerCase().indexOf(searchTerm.toLowerCase()) == 0) {
            matchedData.push(chosenValues[i]);
        }
        else {
            unMatchedData.push(chosenValues[i]);
        }       
    }
     matchedData.sort();
     unMatchedData.sort();
     return (matchedData.concat(unMatchedData));
}
Shiv Patne
  • 543
  • 3
  • 10