Functionality Overview
The Custom Search functionality is achieved through JS. The search produces live results for each keypress. This search can be used to filter the data table or HTML table data dynamically, based on the keywords entered. The below code explains the search for the HTML table.
Step 1
Fetch the SharePoint list and store it in an HTML table. The SharePoint list has to be fetched using JavaScript code and stored in an HTML table.
Step 2
Create a HTML search box to get the input keywords.
- <div class="searchBox">
- <input type="text" class="searchTextBox" id="searchTextBoxid" onkeyup="search()" placeholder="Search..." onfocus="this.placeholder = ''" onblur="this.placeholder = 'Search...'"/>
-
- <label id="NotExist" style="display:none"></label> //This label is hidden and used to show a message “Does not exist!” below the search box if searched keyword is not available
- </div>
The onkeyup event is there to capture the typed-in keyword for search and so, in the HTML, the function search() is called for each key press.
Step 3- Search JavaScript Function
- function search()
- {
- var input, filter, table, tr, td, i;
- input = document.getElementById("searchTextBoxid");
- filter = input.value.toUpperCase();
- table =document.getElementById("mainTableid");
- tr = table.getElementsByTagName("tr");
- var countvisble=0;
-
- for(i=0;i<tr.length;i++)
- {
- td=tr[i].getElementsByTagName("td")[0];
- if(td)
- {
- if(td.innerHTML.toUpperCase().indexOf(filter)>-1)
- {
- countvisble++;
- tr[i].style.display="";
- document.getElementById("NotExist").style.display = "none";
- }
- else
- {
- tr[i].style.display = "none";
- document.getElementById("NotExist").style.display = "none";
- }
- }
- }
- if(countvisble==0)
- {
- document.getElementById("NotExist").style.display = "Block";
- document.getElementById("NotExist").innerHTML = "Does not exist!";
- }
- }
Step 4- Implement the search in the required page
Add the search box HTML code on your page and add the required CSS for the search box style.
Step 5- Search Demo Results
The table content changes based on the keyword typed; only those items that match the typed keyword will get displayed in the HTML table and other rows get hidden.
From the list of 8 items, on typing the keyword “k”, the data gets filtered dynamically and the HTML table shows only 2 items that have the keyword.
For the keyword “ka”, the existing 2 items get filtered and only one item that matched the keyword gets displayed dynamically in the HTML table.
If the typed-in keyword does not match with any of the items in the HTML table, then an alert message will be displayed with the blank table, as shown below.