Reputation:
I am developing a music player using JavaScript and I am trying to add a search bar to my page but every tutorial I have seen so far uses a list created in the HTML page, whereas I have created a list using JavaScript code like this:
const songs = [
"BlindingLights.mp3",
"Boyfriend.mp3",
"DontStartNow.mp3",
"Intentions.mp3",
"Physical"
]
const createSongList = () => {
const list = document.createElement('ol')
for(let i = 0; i<songs.length; i++){
const item = document.createElement('li')
item.appendChild(document.createTextNode(songs[i]))
list.appendChild(item)
}
return list
}
document.getElementById('songList').appendChild(createSongList())
Is there a way I can use the 'songs' array or to develop a search function? Any advice would be appreciated. Thanks! :)
Edit for clarity:
So I have an input tag on my html that I want to use for a search bar, then I want what the user types in to return any matching songs from the songs array. For example if they type in 'Bli' I want it to show the Blinding Lights song. The code snippet above is how I am currently displaying a list of songs using the array.
This is my input tag:
<input type="text" name="searchBar" id="searchBar" placeholder="Search" onkeyup="searchBar()">
Upvotes: 1
Views: 884
Reputation: 1299
Maybe you can create a new function search
to Array.prototype to make it used more easily
Array.prototype.search = function (keyword) {
return this.filter(text => text.toLowerCase().includes(keyword.toLowerCase().trim()))
}
const songs = [
"BlindingLights.mp3",
"Boyfriend.mp6",
"DontStartNow.mp5",
"Intentions.mp3",
"Physical"
];
songs.search('phy ') // => ["Physical"]
songs.search(' MP3') // => ["BlindingLights.mp3", "Intentions.mp3"]
Upvotes: 0
Reputation: 1036
Assuming that you want to filter songs
array from a search string, you can use this function :
const songs = [
"BlindingLights.mp3",
"Boyfriend.mp3",
"DontStartNow.mp3",
"Intentions.mp3",
"Physical"
];
const searchSong = (value) => {
return songs.filter(song => song.includes(value));
};
console.log(searchSong('B'));
Upvotes: 2