i'm using the jquery-select2 plugin but i'm wondering how can i get only results that begins with the typed keyword ( like 'myString%')
Asked
Active
Viewed 3,905 times
3
-
Please provide some sourcecode showing your problem in detail and what you already set up. – mayrs Apr 04 '13 at 11:27
1 Answers
11
The documentation actually provides an example for that:
$("select").select2({
matcher: function(term, text) {
return text.toUpperCase().indexOf(term.toUpperCase())==0;
}
});
The above matcher is case-insensitive, for case-sensitive remove both .toUpperCase()
calls.

Fabrício Matté
- 69,329
- 26
- 129
- 166
-
now it's work for me, i use : matcher: function(term, text) { return text.toUpperCase().indexOf(term.toUpperCase())==1; } – user2224150 Apr 04 '13 at 13:50
-
`indexOf` returns the position in which the term started matching the item's text. `0` is the start of the string while `1` corresponds to the second character of the string (maybe you have some whitespace inside the option's text?). Well glad it worked. `=]` – Fabrício Matté Apr 04 '13 at 14:32
-
you are right Sir, i found a whitespace in the option text as you told me thanks a lot for your help – user2224150 Apr 04 '13 at 14:49
-
To ignore whitespaces you may call `.trim()` before or after `.toUpperCase()` both places. – Izhar Aazmi Apr 25 '15 at 11:09