זהו דוגמת קוד בהמשך למאמר : "אפליקציות JS שימושיות " בדוגמא זו , החיפוש מתבצע בתוך תיבת Select אבל מה שנשאר בתיבה הן אך ורק התוצאות ובמידה ואינו מוצא כלום אנו מיודעים גם ..
אז ככה :
arrLength = 0; // the length of the array (global var)
var select_box = new Array(0); // array of the select menu
חלק זה מגדיר שני משתנים , האחד את גודל המערך שנימצא בתוך ה select והשני הוא המערך עצמו.
הם מוגדרים מחוץ לפונקציה מכיוון שאנו רוצים שהערכים ישמרו לאורך כל הדרך ולא רק בתוך פונקציה.
function GetList()
{ // get a list from the select menu into an array...
window.document.myform.search.focus();
arrLength = document.myform.selectmenu.options.length;
select_box = new Array(arrLength);
for (i = 0 ; i < arrLength ; i++)
{
select_box[i] = document.myform.selectmenu.options[i].text;
}
}
פונקציה זאת מקבלת את כל הערכים של ה select לתוך מערך שהגדרנו מקודם..כך אנחנו יכולים למחוק את הערכים בתוך התיבה ולהציג רק את התוצאות .. במידה ולא היינו שומרים לא היה ניתן לבצע את "המחיקה" של הערכים שלא מתאימים לחיפוש..
function Search()
{
//search within the array to see if the search string exists...
sSearch = document.myform.search.value;
sSearch = sSearch.toLowerCase(); // search string from input box..
iFound = 0; //num of results...
document.myform.selectmenu.options.length = 0; //clear the select menu
for (i = 0 ; i < arrLength ; i++)
{
//lowercase everything..
sSelectValue = select_box_text[i];
sSelectValue = sSelectValue.substring(0,sSearch.length);
sSelectValue = sSelectValue.toLowerCase();
if (sSelectValue == sSearch)
{
// write inside the select only if it's found....
document.myform.selectmenu.options.length = iFound + 1;
document.myform.selectmenu.options[iFound].value = select_box_values[i];
document.myform.selectmenu.options[iFound].text = select_box_text[i];
iFound = iFound + 1;
}
}
if (iFound == 0) // message if nothing was found..
{
document.myform.selectmenu.options.length = iFound + 1;
document.myform.selectmenu.options[iFound].text = "nothing was found";
iFound = iFound + 1;
}
document.myform.selectmenu.options.length = iFound + 1;
document.myform.selectmenu.options[iFound].value = "";
document.myform.selectmenu.options[iFound].text = "-------------------------------------" ;
}
פונקציה זאת עושה את החיפוש בתוך המערך..היא מקבלת את הערך שהמשתמש הכניס והופכת אותו לאותיות קטנות.
אנו מגדירים משתנה נוסף לבדוק כמה תוצאות קיבלנו גם כדי שהדפסת התוצאות תפגם וגם כדי שנדע במידה ואנו לא מוצאים כלום.
מאפסים את ה select כך שרק התוצאות שלנו יופיעו (תודה לנועם!) עוברים על כל המערך. עבור כל ערך מהמערך , אנו הופכים אותו לאותיות קטנות וחותכים ממנו את את אורך המילה שהמשתמש הקליד... משווים בין שתי התוצאות במידה והם מתאימים , מדפיסים את התוצאה.
קטע זה בא להעביר את כל הנתונים למערך לפני שאנו נוגעים בו (כמו שתואר למעלה)
קטע זה הולך לפונקציית החיפוש לאחר כל הקלדה ובנוסף מבטל את ה autocomplete דבר שעלול להפריע במצב כזה..
בנוסף , ביטול הקשת ה enter...