2

I am creating website of student community. Having difficulty in adding Search Bar option to website. I can add normal for search but had bug for all together.

How should I add name search here?


const search = async()=> {
 let input = document.querySelector(".input").value
 let searchContainer = ''

 const res = await getAllStudent()
 let response = res.data.students

 let searchTrack = response.filter(item => {
 return input === item.name || parseInt(input) === item.stuId || parseInt(input) === item.circle
   
})
  searchTrack.length > 0?

  searchTrack.forEach((searchItem, index) => {
    const {id,name, stuId, track, img, description, socialmedia:{linkedin, github, twitter, portfolio}} = searchItem;
    

    let newIndex = index+id;
    
Kdhere
  • 65
  • 1
  • 7
  • Why don't you use a JS search library, like FuseJS and then just display the results? – Kallikratidas Aug 26 '22 at 18:11
  • 1
    Please do not include off site resources in your questions as they have a tendency to disappear and/or require additional sign-ups rendering your question incomplete. You need to include enough information in your question itself to reproduce the problem. (i.e. an [mre]) – Tibrogargan Aug 26 '22 at 18:13
  • Sure TIbrogargan I will remember that. – Kdhere Aug 26 '22 at 18:14
  • **I tried Fuesjs but I want to learn more about Js so trying for traditional methods.** – Kdhere Aug 26 '22 at 18:17

2 Answers2

1

Because you already have the names on the page, you do not need to fetch them again to search for them.

The following function searches every card for the value you enter in the search bar, and only shows the cards that include that value. Keep in mind that the function searches the entire <div class="profile-card">...</div>, so anything on both sides of the card will be searched.

function search() {
    let input = document.querySelector(".input").value
    input = input.toLowerCase();
    let x = document.getElementsByClassName('profile-card');

    for (i = 0; i < x.length; i++) {
        if (!x[i].innerHTML.toLowerCase().includes(input)) {
            x[i].style.display = "none";
        }
        else {
            x[i].style.display = "block";
        }
    }
}

css-tricks has an article that explains this a little better.

Good luck!

0

Here are some extra functions:

const stringLowerCase = (value) => value.toString().toLowerCase();

const isMatched = (value, matchBy) => stringLowerCase(value).match(stringLowerCase(matchBy));

Then I updated your filter code:

let searchTrack = response.filter( (item) => isMatched(item.name, input) || isMatched(item.stuId, input) || isMatched(item.circle, input) );
Vijay Hardaha
  • 2,411
  • 1
  • 7
  • 16
  • Additional Tips: - Don't use `onClick` on `` tag use it on ` – Vijay Hardaha Aug 26 '22 at 18:31
  • **This the answer I was trying for.** – Kdhere Aug 26 '22 at 18:46