Hi I have a div in html (searchlist) which is filtered using the javascript below from the content of an input box (id searchbar) is it possible to also set .style.display=“none” if the input box is empty?
<script type="text/javascript">
//search site for pages
function search_sitemap() {
let input = document.getElementById('searchbar').value
input=input.toLowerCase();
let x = document.getElementsByClassName('pages');
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";
}
}
}
</script>
Hi @ldarley! There are some issues here. I’ll list them for your convenience:
Imperative vs. declarative. It’s commonly agreed that declarative practices are less error-prone and more efficient. So, instead of having a list of anchors that you would try to control (with CSS ) with searchbar you could say 'OK, here’s an array of anchors and I will always show it taking info consideration .filter method that is always attached to that array.
I would argue against .includes for searching text content. For example:
const a = 'blue shiny car'
a.includes('blue car') // false
You need a word-based comparison, not a sub-string one
Wow thanks for your response, Javascript is hard I thought I was close too as it looked like nice all formatted with CSS but I guess I am miles away! I had assumed there was a way to add another if condition in vba I would do something like if isblank(input) then… but I assume this type of condition is not then possible?
I am struggling with the .filter function though as I can’t figure out how the if condition should work or the return element, I may be way away hopefully you can point out where.
function search_sitemap() {
let input = document.getElementById('searchbar').value
input=input.toLowerCase();
var shortlist = search_sitemap.filter(function (page){
if(!input || pages.keyword.toLowerCase().indexOf(input)!==-1){
return '<a href="$[$href).text()}">${$(title).text()}</a>'
};
});
$('#search_output').html(search_sitemap);