I have a list of items in a drop down which is filterable using a search within the dropdown.
<div class="dropdown">
<button onclick="myFunction()" class="dropbtn">Please select</button>
<div id="myDropdown" class="dropdown-content">
<input type="text" placeholder="Search.." id="myInput" onkeyup="filterFunction()">
Abyssinian
American Bobtail
Amercian Curl
</div>
</div>
And the js...
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
function filterFunction() {
var input, filter, ul, li, a, i;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
div = document.getElementById("myDropdown");
a = div.getElementsByTagName("a");
for (i = 0; i < a.length; i++) {
txtValue = a[i].textContent || a[i].innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
a[i].style.display = "";
} else {
a[i].style.display = "none";
}
}
}
https://codepen.io/RSA_James/pen/LYZqYym
What I'm after is a way of showing a message if a user starts searching for something and there's no matches.
Any help appreciated! Thanks
ES6 shrinks the code a bit:
function filterFunction(sText) {
[...document.querySelectorAll('#myDropdown a')].forEach(elA => elA.classList.toggle('hide', !new RegExp(sText, 'gi').test(elA.textContent)));
document.querySelector('#myDropdown span.err').classList.toggle('hide', document.querySelectorAll('#myDropdown a:not(.hide)').length);
}
.hide { display: none; } .err { color: red; }
<div class="dropdown">
<button onclick="myFunction()" class="dropbtn">Please select</button>
<div id="myDropdown" class="dropdown-content">
<input type="text" placeholder="Search.." id="myInput" oninput="filterFunction(this.value)">
Abyssinian
American Bobtail
Amercian Curl
<span class="err hide">Nothing found</span>
</div>
</div>
Have a look here, added some new code and created a new element when there is no found result.
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
function filterFunction() {
var input, filter, ul, li, a, i;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
div = document.getElementById("myDropdown");
a = div.getElementsByTagName("a");
var empty = document.createElement("a");
empty.classList.add("empty");
empty.innerHTML="No Reault Found...";
var emptyVisiable= true;
for (i = 0; i < a.length; i++) {
txtValue = a[i].textContent || a[i].innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
a[i].style.display = "";
emptyVisiable = false;
} else {
a[i].style.display = "none";
}
}
if (emptyVisiable)
div.appendChild(empty);
else {
empty= div.querySelector(".empty")
if (empty!== null)
empty.remove();
}
}
.dropbtn {
background-color: #e3e3e3;
background-image: url('https://image.flaticon.com/icons/png/512/25/25243.png');
background-position: 270px center;
background-repeat: no-repeat;
background-size: 5%;
color: #333 ;
border: 1px solid red;
border-radius: 5px;
min-width: 300px;
padding: 16px;
font-size: 16px;
border: none;
cursor: pointer;
text-align: left;
}
.dropbtn:hover, .dropbtn:focus {
background-color: #d3d3d3;
}
#myInput {
box-sizing: border-box;
background-image: url('https://www.w3schools.com/howto/searchicon.png');
background-position: 14px 12px;
background-repeat: no-repeat;
font-size: 16px;
padding: 14px 20px 12px 45px;
border: none;
border-bottom: 1px solid #ddd;
width: 100%;
}
#myInput:focus {outline: 3px solid #ddd;}
.dropdown {
position: relative;
display: inline-block;
}
.dropdown-content {
display: none;
position: absolute;
background-color: #f6f6f6;
min-width: 230px;
width: 100%;
max-height: 260px;
overflow: auto;
border: 1px solid #ddd;
z-index: 1;
}
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
.dropdown a:hover {background-color: #ddd;}
.show {display: block;}
<h2>Search/Filter Dropdown</h2>
<p>Click on the button to open the dropdown menu, and use the input field to search for a specific dropdown link.</p>
<div class="dropdown">
<button onclick="myFunction()" class="dropbtn">Please select</button>
<div id="myDropdown" class="dropdown-content">
<input type="text" placeholder="Search.." id="myInput" onkeyup="filterFunction()">
Abyssinian
American Bobtail
Amercian Curl
American Longhair
American Shorthair
American Wirehair
Angora
Asian
Asian Blue
Balinese
Bengal
Bengal Tiger
Bicolour
Bicolour Longhair
British Bicolour Shorthair
Birman
Black
Black and White
Black and White Longhair
Black and White Shorthair
Black Longhair
Black Shorthair British Black
</div>
</div>
you can accomplish this by adding a p tag for the error in the html and a counter that increments each time no res is found in the loop of your filter function followed by an if at the end that checks to see if the counter === the lengths of links
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
function filterFunction() {
var input, filter, ul, li, a, i;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
div = document.getElementById("myDropdown");
a = div.getElementsByTagName("a");
let count = 0;
for (i = 0; i < a.length; i++) {
txtValue = a[i].textContent || a[i].innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
a[i].style.display = "";
} else {
count++;
a[i].style.display = "none";
}
}
if(count == a.length )
displayNoResults(filter);
}
function displayNoResults(searchTxt) {
let noResFound = document.getElementById("noResFound");
noResFound.style.display = "block"
noResFound.innerHTML = `No results for "${searchTxt}" were found`
}
<div class="dropdown">
<button onclick="myFunction()" class="dropbtn">Please select</button>
<div id="myDropdown" class="dropdown-content">
<input type="text" placeholder="Search.." id="myInput" onkeyup="filterFunction()">
<p id="noResFound"></p>
Abyssinian
American Bobtail
Amercian Curl
</div>
</div>
Related
Basically, this code makes it so that all results show and get trimmed down when you search for something specific. I want to hide all results before I've started writing and when I've entered at least one letter results show up again. I've been stuck at that exact problem for hours and have concluded with nothing.
I'd really appreciate the help.
function Function() {
var input, filter, ul, li, a, i, txtValue;
input = document.getElementById('Input');
filter = input.value.toUpperCase();
ul = document.getElementById("UL");
li = ul.getElementsByTagName('li');
for (i = 0; i < li.length; i++) {
a = li[i].getElementsByTagName("a")[0];
txtValue = a.textContent || a.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
li[i].style.display = "";
} else {
li[i].style.display = "none";
}
}
}
#Input {
background-image: url('/css/searchicon.png');
background-position: 10px 12px;
background-repeat: no-repeat;
width: 30%;
font-size: 16px;
padding: 12px 20px 12px 40px;
border: 1px solid #ddd;
justify-content: center;
height: 20px;
}
#media screen and (max-width: 600px) {
#Input {
width: 80%;
margin-top: 4px;
}
}
;
#UL {
list-style-type: none;
padding: 0;
margin: 0;
}
#UL li a {
border: 1px solid #ddd;
margin-top: -1px;
background-color: #f6f6f6;
padding: 12px;
width: 30%;
text-decoration: none;
font-size: 18px;
color: black;
display: block;
}
#UL li a:hover:not(.header) {
background-color: #eee;
}
<input type="text" id="Input" onkeyup="Function()" placeholder="Search...">
<ul id="UL" style="list-style: none;">
<li class="listClass">SONY a6000</li>
<li class="listClass">SONY a6400</li>
<li class="listClass">SONY a7 IV</li>
<li class="listClass">Canon EOS RP</li>
<li class="listClass">Nikon D3500</li>
<li class="listClass">Hasselblad X1D II 50C</li>
</ul>
Given your html structure you can do this in one line of css:
#Input:focus:placeholder-shown + ul {
display:none;
}
It works because you have placeholder text on your input element, and the <ul> is adjacent to it. Read more here:
https://developer.mozilla.org/en-US/docs/Web/CSS/:placeholder-shown
https://developer.mozilla.org/en-US/docs/Web/CSS/Adjacent_sibling_combinator
If I understand correctly, Initially all the results will be shown? Then when you start typing they will be hidden(not entered any letter) and after entering atleast one element they start showing again? In that case you can use onfocus event along with onkeyup event.
function Function() {
let input, filter, ul, li, a, i, txtValue;
input = document.getElementById('Input');
filter = input.value.toUpperCase();
ul = document.getElementById("UL");
li = ul.getElementsByTagName('li');
for (i = 0; i < li.length; i++) {
a = li[i].getElementsByTagName("a")[0];
txtValue = a.textContent || a.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1 && filter!=='') {
li[i].style.display = "";
} else {
li[i].style.display = "none";
}
}
}
#Input {
background-image: url('/css/searchicon.png');
background-position: 10px 12px;
background-repeat: no-repeat;
width: 30%;
font-size: 16px;
padding: 12px 20px 12px 40px;
border: 1px solid #ddd;
justify-content: center;
height: 20px;
}
#media screen and (max-width: 600px) {
#Input {
width: 80%;
margin-top: 4px;
}
}
;
#UL {
list-style-type: none;
padding: 0;
margin: 0;
}
#UL li a {
border: 1px solid #ddd;
margin-top: -1px;
background-color: #f6f6f6;
padding: 12px;
width: 30%;
text-decoration: none;
font-size: 18px;
color: black;
display: block;
}
#UL li a:hover:not(.header) {
background-color: #eee;
}
<input type="text" id="Input" onkeyup="Function()" onfocus="Function()" placeholder="Search...">
<ul id="UL" style="list-style: none;">
<li class="listClass">SONY a6000</li>
<li class="listClass">SONY a6400</li>
<li class="listClass">SONY a7 IV</li>
<li class="listClass">Canon EOS RP</li>
<li class="listClass">Nikon D3500</li>
<li class="listClass">Hasselblad X1D II 50C</li>
</ul>
If you want to show all the results again when unfocusing the input field (and not any letter in the input field) then you can use onblur event to achieve that as well by modifying input field like below and add the function.
function Function2()
{
let input, filter, ul, li, a, i, txtValue;
input = document.getElementById('Input');
filter = input.value.toUpperCase();
ul = document.getElementById("UL");
li = ul.getElementsByTagName('li');
for (i = 0; i < li.length; i++) {
a = li[i].getElementsByTagName("a")[0];
txtValue = a.textContent || a.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
li[i].style.display = "";
} else {
li[i].style.display = "none";
}
}
}
<input type="text" id="Input" onkeyup="Function()" onfocus="Function()" onblur="Function2()" placeholder="Search...">
I have created a searchbox and I have made it absolute and added one more text box on the bottom , I am unable to click and enter the value in the text box.
Note: Position must be the same, Click for the Second Text box is not working
Here is the jsFiddle Link
Here is the code snippet
var placeArr = ["Adele","Agnes","Billy","Bob","Calvin","Christina","Cindy"];
function myFunction() {
let input, filter, ul, li, liElem, i, txtValue;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
ul = document.getElementById("myUL");
li = ul.getElementsByTagName("li");
for (i = 0; i < li.length; i++) {
liElem = li[i];
txtValue = liElem.textContent || liElem.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
li[i].style.display = "block";
} else {
li[i].style.display = "none";
}
}
}
function showDiv(){
let liList=(document.getElementById("myUL")).getElementsByTagName("li");
for(var i=0;i<liList.length;i++){
(liList[i]).style.display="block";
}
}
function hideDiv(){
let liList=(document.getElementById("myUL")).getElementsByTagName("li");
for(var i=0;i<liList.length;i++){
(liList[i]).style.display="none";
}
}
var selectPlace = function(ids){
document.getElementById("myInput").value=document.getElementById(ids).innerHTML;
hideDiv();
}
var generateList = function(array, eventfn){
let cnt=0;
array.forEach(function(item){
var node = document.createElement("LI"); // Create a <li> node
var textnode = document.createTextNode(item); // Create a text node
node.appendChild(textnode);
node.setAttribute("id", "myLi"+(cnt++));
node.addEventListener("click", ()=>{eventfn(node.getAttribute("id"))});
document.getElementById("myUL").appendChild(node);
});
};
generateList(placeArr,selectPlace);
* {
box-sizing: border-box;
}
#myInput,.myInput {
background-position: 10px 12px;
background-repeat: no-repeat;
width: 50%;
font-size: 16px;
padding: 12px 20px 12px 10px;
border: 1px solid #ddd;
}
#myUL {
list-style-type: none;
padding: 0;
margin: 0;
width:50%;
height:200px;
overflow-y:auto;
position:absolute;
}
#myUL li {
border: 1px solid #ddd;
margin-top: -1px; /* Prevent double borders */
background-color: #f6f6f6;
padding: 12px;
text-decoration: none;
font-size: 18px;
color: black;
display: none;
}
#myUL li a:hover:not(.header) {
background-color: #eee;
}
<h2>My Phonebook</h2>
<div>
<input type="text" id="myInput" class="myInput" onkeyup="myFunction()" onclick=showDiv() placeholder="Search for names.." title="Type in a name">
<ul id="myUL">
</ul>
</div>
<br/>
<div>
<input type="text" class="myInput">
</div>
I have added the Image
Currently, your ul tag is overriding the div underneath. So for:
<div style="z-index: 1; position: relative;">
<input type="text" class="myInput">
</div>
just add the z-index and position to have it on top. You will have to add in a style to the ul tag though onclick to override it when it is in use.
.override{
z-index: 10;
position: relative;
}
function showDiv(){
let liList=(document.getElementById("myUL")).getElementsByTagName("li");
for(var i=0;i<liList.length;i++){
(liList[i]).style.display="block";
}
li = document.getElementById('myUL'); // added this line
li.classList.add("override"); // added this line
}
function hideDiv(){
let liList=(document.getElementById("myUL")).getElementsByTagName("li");
for(var i=0;i<liList.length;i++){
(liList[i]).style.display="none";
}
li = document.getElementById('myUL'); // added this line
li.classList.remove("override"); // added this line
}
https://jsfiddle.net/tgq65jas/
The second text box is being obscured by the myUL element. In the hideDiv function, each of the li elements have their display set to none, but myUL is still there.
Rather than setting display: none for each li, set display: none on the entire ul.
I have this dropdown menu:
document.addEventListener("DOMContentLoaded", function(event) {
allNameMuseums().forEach(function(item) { // ITERAZIONE
document.getElementById("myDropdown").innerHTML += '<a onclick="updateData(this)">' + item + '</a>';
})
});
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
function filterFunction() {
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
div = document.getElementById("myDropdown");
a = div.getElementsByTagName("a");
for (i = 0; i < a.length; i++) {
if (a[i].innerHTML.toUpperCase().indexOf(filter) > -1) {
a[i].style.display = "";
} else {
a[i].style.display = "none";
}
}
}
<div class="dropdown">
<button onclick="myFunction()" class="dropbtn">Museo1</button>
<div id="myDropdown" class="dropdown-content">
<input type="text" placeholder="Search.." id="myInput" onkeyup="filterFunction()">
</div>
</div>
I want that when I click an item in the list of dropdown menu, the list closes automatically.
What are you need is remove the "show" class from the element.
Example:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.dropbtn { background-color: #4CAF50; color: white; padding: 16px; font-size: 16px; border: none; cursor: pointer; }
.dropbtn:hover, .dropbtn:focus { background-color: #3e8e41; }
#myInput { border-box: box-sizing; background-image: url('searchicon.png'); background-position: 14px 12px; background-repeat: no-repeat; font-size: 16px; padding: 14px 20px 12px 45px; border: none; border-bottom: 1px solid #ddd; }
#myInput:focus { outline: 3px solid #ddd; }
.dropdown { position: relative; display: inline-block; }
.dropdown-content { display: none; position: absolute; background-color: #f6f6f6; min-width: 230px; overflow: auto; border: 1px solid #ddd; z-index: 1; }
.dropdown-content a { color: black; padding: 12px 16px; text-decoration: none; display: block; }
.dropdown a:hover { background-color: #ddd; }
.show { display: block; }
</style>
</head>
<body>
<h2>Search/Filter Dropdown</h2>
<p>Click on the button to open the dropdown menu [...]</p>
<div class="dropdown">
<button onclick="myFunction()" class="dropbtn">Dropdown</button>
<div id="myDropdown" class="dropdown-content">
<input type="text" placeholder="Search.." id="myInput" onkeyup="filterFunction()">
Item1
Item2
</div>
</div>
<script>
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
function filterFunction() {
var input, filter, ul, li, a, i;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
div = document.getElementById("myDropdown");
a = div.getElementsByTagName("a");
for (i = 0; i < a.length; i++) {
if (a[i].innerHTML.toUpperCase().indexOf(filter) > -1) {
a[i].style.display = "";
} else {
a[i].style.display = "none";
}
}
}
function select() {
//Your item selection logic here...
myFunction();
}
</script>
</body>
</html>
Follow the example in W3C School here:
What you are missing is, closing the dropdown when the click is outside the button:
// Close the dropdown if the user clicks outside of it
window.onclick = function(event) {
if (!event.target.matches('.dropbtn')) {
var dropdowns = document.getElementsByClassName("dropdown-content");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
}
}
Try yourself
And notice, this example doesn't have your search bar, so in this function, you'll have to check with the search bar as well to exclude it from closing the drop down.
I just implemented a Search / Filter Dropdown, following this guide: https://www.w3schools.com/howto/tryit.asp?filename=tryhow_css_js_dropdown_filter.
<h2>Search/Filter Dropdown</h2>
<p>Click on the button to open the dropdown menu, and use the input field to search for a specific dropdown link.</p>
<div class="dropdown">
<button onclick="myFunction()" class="dropbtn">Dropdown</button>
<div id="myDropdown" class="dropdown-content">
<input type="text" placeholder="Search.." id="myInput" onkeyup="filterFunction()">
</div>
</div>
This Search / Filter Dropdown takes the array of the allNameMuseums () method as values, ie ["ACQUARIUM", "Museo2", "Museo3"].
document.addEventListener("DOMContentLoaded", function(event) {
allNameMuseums().forEach(function(item) {
document.getElementById("myDropdown").innerHTML += '' + item + '';
})
});
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
function filterFunction() {
var input, filter, ul, li, a, i;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
div = document.getElementById("myDropdown");
a = div.getElementsByTagName("a");
for (i = 0; i < a.length; i++) {
if (a[i].innerHTML.toUpperCase().indexOf(filter) > -1) {
a[i].style.display = "";
} else {
a[i].style.display = "none";
}
}
}
function allNameMuseums() {
return ["ACQUARIO", "Museo2", "Museo3"];
}
I have two asynchronous methods, specificoMuseo(name) and allMuseums (), and a variable var data = proof; that takes the result of the allMuseums() method.
specificoMuseo(name).then(proof2 => {
allMuseums().then(proof => {
var data = proof;
});
});
I want that when I click on ACQUARIO of Search / Filter Dropdown the variable 'data' takes as input the result of specificoMuseo ("ACQUARIO").
You need to similar logic as below,
var name; //globle variable so you can access in your method
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
function fnclick(obj) {
name = obj.innerHTML;
alert(name);
console.log(name);
}
function filterFunction() {
var input, filter, ul, li, a, i;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
div = document.getElementById("myDropdown");
a = div.getElementsByTagName("a");
for (i = 0; i < a.length; i++) {
if (a[i].innerHTML.toUpperCase().indexOf(filter) > -1) {
a[i].style.display = "";
} else {
a[i].style.display = "none";
}
}
}
.dropbtn {
background-color: #4CAF50;
color: white;
padding: 16px;
font-size: 16px;
border: none;
cursor: pointer;
}
.dropbtn:hover, .dropbtn:focus {
background-color: #3e8e41;
}
#myInput {
border-box: box-sizing;
background-image: url('searchicon.png');
background-position: 14px 12px;
background-repeat: no-repeat;
font-size: 16px;
padding: 14px 20px 12px 45px;
border: none;
border-bottom: 1px solid #ddd;
}
#myInput:focus {outline: 3px solid #ddd;}
.dropdown {
position: relative;
display: inline-block;
}
.dropdown-content {
display: none;
position: absolute;
background-color: #f6f6f6;
min-width: 230px;
overflow: auto;
border: 1px solid #ddd;
z-index: 1;
}
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
.dropdown a:hover {background-color: #ddd;}
.show {display: block;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>Search/Filter Dropdown</h2>
<p>Click on the button to open the dropdown menu, and use the input field to search for a specific dropdown link.</p>
<div class="dropdown">
<button onclick="myFunction()" class="dropbtn">Dropdown</button>
<div id="myDropdown" class="dropdown-content">
<input type="text" placeholder="Search.." id="myInput" onkeyup="filterFunction()">
About
Base
Blog
</div>
</div>
I am trying make the drop-down visible only when something is entered in the search bar.Otherwise it stays collapsed. Following is my code
function mysearchFunction() {
var input, upperCase, ul, li, x, i, ax;
input = document.getElementById("mysearchInput");
upperCase = input.value.toUpperCase();
ul = document.getElementById("myList");
li = ul.getElementsByTagName("li");
for (i = 0; i < li.length; i++) {
x = li[i].getElementsByTagName("a")[0];
if (x.innerHTML.toUpperCase().indexOf(upperCase) === 0) {
li[i].style.visibility = "visible";
li[i].style.display = "block";
} else {
li[i].style.display = "none";
}
}
}
#myList li a {
border: 1px solid #ddd;
margin-top: -2px;
background-color: #f6f6f6;
padding: 10px;
text-decoration: none;
font-size: 16px;
color: black;
display: block;
visibility: collapse;
}
<input type="text" id="mysearchInput" onkeyup="mysearchFunction()" placeholder="Search..">
<ul id="myList">
<li>America</li>
<li>Africa</li>
<li>Antartica</li>
<li>Asia</li>
<li>Europe</li>
<li>Australia</li>
</ul>
In the JS, I am trying to make only content that needs to be displayed as visible. Kindly guide me where I am going wrong. No content is currently being displayed. It is staying collapsed.
Just updated the css selector: #myList li, you were hiding all the links.
function mysearchFunction() {
var input, upperCase, ul, li, x, i, ax;
input = document.getElementById("mysearchInput");
upperCase = input.value.toUpperCase();
//console.log(upperCase);
ul = document.getElementById("myList");
li = ul.getElementsByTagName("li");
for (i = 0; i < li.length; i++) {
x = li[i].getElementsByTagName("a")[0];
if (x.innerHTML.toUpperCase().indexOf(upperCase) == 0 && upperCase !== '') {
li[i].style.visibility = "visible";
li[i].style.display = "block";
} else {
li[i].style.display = "none";
}
}
}
#myList li {
border: 1px solid #ddd;
margin-top: -2px;
background-color: #f6f6f6;
padding: 10px;
text-decoration: none;
font-size: 16px;
color: black;
display: block;
visibility: collapse;
}
<input type="text" id="mysearchInput" onkeyup="mysearchFunction()" placeholder="Search..">
<ul id="myList">
<li>America</li>
<li>Africa</li>
<li>Antartica</li>
<li>Asia</li>
<li>Europe</li>
<li>Australia</li>
</ul>