'How to hide a element if input is empty?
I'm a student learning in javascript and I'm trying to build a search function.
I have multiple html figure with pictures. I'm filtering the figures with a input and with the figcaptions.
I'm trying to hide the figures that don't match with value that is put into the input.
But I have a figure that already has a css display:none;.
And when you search for this certain figure it pops up but after the input is empty again the figure stays visible.
I tried to reset the css by using obj.style.display = "" and obj.style.display = "none".
But that didn't work.
Briefly my goal is to hide a figure until it matches the value of input, but if input is empty it should be hidden again.
Any help would be appreciated, thank you!
// entire code can be found here: https://codepen.io/Yung_n-d/pen/mdwQGqX
//Javascript
function myFunction() {
var input, filter, ul, li, a, i, txtValue, getSpecial;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
ul = document.getElementById("background");
li = ul.getElementsByTagName("figure");
getSpecial = document.getElementsByClassName('special');
for (i = 0; i < li.length; i++) {
a = li[i].getElementsByTagName("figcaption")[0];
txtValue = a.textContent || a.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1 ) {
li[i].style.display = "";
} else {
li[i].style.display = "none";
}
if(filter == 0){
getSpecial.style.display = "";
}
}
}
//HTML
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Zoek workshops.." title="Type in a name">
<div id="background">
<div id="gallery">
<figure class="pic1 4-5 6-8 8-12 12+ Dans">
<a href="workshopPages/dans/index.php">
<img src="media/fotos/gallery/Dans.png" />
<figcaption class="test">Dans</figcaption>
</figure>
<figure class="special" style="display: none;" id="8-12" class="pic10 4-5 6-8 8-12 12+ ckv">
<a href="workshopPages/reeks/index.php">
<img src="media/fotos/gallery/reeks.png" />
<figcaption>Film</figcaption>
</figure>
</div>
</div>
Solution 1:[1]
'SomeString'.indexOf('') will return 0 rather than -1; You should also test that the input's value field is not blank.
Change the following line from:
if (txtValue.toUpperCase().indexOf(filter) > -1 ) {
To:
if (filter && txtValue.toUpperCase().indexOf(filter) > -1 ) {
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | factorypolaris |
