David W.
David W.

Reputation: 1083

Changing search behavior in jquery plugin Chosen

I'm using the Chosen plugin for jQuery and would like the search behavior to change a bit (single select). Searching only results in hits where the beginning of a word in the seach string matches. I would like to extend this to also hit words after slash and brackets.

For example: search string: "second" does not match items "first/second" or "first (second)".

I doubt this is changeble by simply adding options to constructor, but I am willing to change/hardcode source script.

Chosen: https://github.com/harvesthq/chosen

Upvotes: 41

Views: 38821

Answers (5)

Lovepreet Singh
Lovepreet Singh

Reputation: 4850

There is option search_contains available to search sub-string in options and can be used as:

$(".chosen-select").chosen({
    search_contains: true
});

Upvotes: 0

Didier Ghys
Didier Ghys

Reputation: 30666

As mentionned in some more recent answers, the plugin now implemements an option to change the search behavior:

search_contains: true

Options documentation


The plugin does not provide an option to change the search method behavior.

If you're willing to change the plugin source itself, here's a way to do it.

The method that makes the search in the plugin is Chosen.prototype.winnow_results. It uses a regular expression that matches text that "starts with" the search term:

// "^": means "starts with"
// "searchText" is the text in the search input (it is just cleaned up don't be scared)
regex = new RegExp('^' + searchText.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"), 'i');

Change it to:

regex = new RegExp(searchText.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"), 'i');

DEMO

Upvotes: 83

Dirk Nguyen
Dirk Nguyen

Reputation: 111

As in Chosen 1.0, just add option {search_contains: true}

$('.selector').chosen({search_contains: true});

Have fun.

Upvotes: 7

Dave Driesmans
Dave Driesmans

Reputation: 819

in chosen 1.0 i did on line 301&302

escapedSearchText = searchText.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
regexAnchor = "";

Upvotes: 0

Lasse Skindstad Ebert
Lasse Skindstad Ebert

Reputation: 3390

The search behavior can be set with the option search_contains

This is by default false

Set it to true, and chosen will also find matches inside instead of only the beginning:

$('#my_dropdown').chosen({ search_contains: true });

Upvotes: 45

Related Questions