Reputation: 11
I want to do a "contains" searching on a list using JavaScript. For example I have a list:
AM Polland AM Certification. AR Ams
Now I have a text box and I have done searching (Starting with) like if I type "A" all the records comes starting with A.
But I want if I type "Pol" then "AM Polland" record should show.
actually i have a big picklist...above that i have a textbox..i want to do seaching based on the letters i type in that textbox.but i want contains searching not starts with.
I don't know how to do that, I am kind of learning JavaScript. Please help with some code.
Upvotes: 0
Views: 2733
Reputation: 167212
There is an autocomplete plugin in jQuery UI. You can make a better use of it.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>jQuery UI Autocomplete - Default functionality</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script src="http://code.jquery.com/ui/1.9.1/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<script>
$(function() {
var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
"Groovy",
"Haskell",
"Java",
"JavaScript",
"Lisp",
"Perl",
"PHP",
"Python",
"Ruby",
"Scala",
"Scheme"
];
$( "#tags" ).autocomplete({
source: availableTags
});
});
</script>
</head>
<body>
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags" />
</div>
</body>
</html>
Upvotes: 1
Reputation: 324760
I'm guessing your current code just checks the substr
of the appropriate length. What you need for this is a regex.
// first, a helper function to escape regex characters. Source: phpJS
function preg_quote(str) {
return (str + '').replace(/[.\\+*?\[\^\]$(){}=!<>|:\-]/g, '\\$&');
}
// create the regex (assuming "input" is the variable containing the search string)
var regex = new RegExp(preg_quote(input)), i;
// now search for it (assuming "list" is the array of strings containing the data)
for( i in list) {
if( list.hasOwnProperty(i)) {
if( list[i].match(regex)) {
// it's a match! do something with it
}
}
}
Upvotes: 0