简体   繁体   中英

How to display selected item from drop down using html, css and javascript

I have a drop down list where list of countries is being fetched from JSON array. Drop down list is coming from dynamic json object. I have applied search in that drop down list. I am trying to display the selected item but I am unable to do it. I want that when I select a particular country from the list it get displayed.

 function myFunction() { var country = [{ "ID": "001", "Country_Name": "India" }, { "ID": "002", "Country_Name": "Australia" }, { "ID": "003", "Country_Name": "Austria" }, { "ID": "004", "Country_Name": "China" }, { "ID": "005", "Country_Name": "Bangladesh" } ]; document.getElementById("myDropdown").classList.toggle("show"); var ele = document.getElementById("myDropdown"); for (var i = 0; i <= country.length; i++) { ele.innerHTML = ele.innerHTML + '<a value="' + country[i]['ID'] + '">' + country[i] ['Country_Name'] + '</a>'; } } 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"; } } }
 #myInput { box-sizing: border-box; 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; } position: relative; display: inline-block; } .dropdown-content { display: none; position: absolute; background-color: #f6f6f6; min-width: 230px; border: 1px solid #ddd; z-index: 1; } .dropdown-content a { color: black; padding: 12px 16px; text-decoration: none; display: block; } .dropdown-content a:hover { background-color: #f1f1f1 } .show { display: block; }
 <div class="dropdown"> <button onclick="myFunction()" class "dropbtn"> Dropdown </button> <div id="myDropdown" class="dropdown-content" onclick="show()"> <input type="text" placeholder="Search..." id="myInput" onkeyup="filterFunction()"> <a value=""></a> </div> </div>

Your code had a couple of errors:

  • <div id="myDropdown" class="dropdown-content" onclick="show()"> but show() is not defined so I removed the onclick handler;
  • for (i = 0; i <= a.length; i++) should be instead i < a.length

Plus I better refactored the part where you built the anchor elements so that instead of using the innerHTML strategy, those elements get created with document.createElement() . That way there's the chance to have a reference to the object and add a click event handler to each option, so that when you click a Country, its name gets displayed on console.

The country option click handler was defined as the countryOnClick() function and so far it justs displays the clicked option data on console. You are free to change it anyway you like to perform the action you better prefer.

Each option will have the class dropdown-option and when an option is selected will have the class optionSelected . To query the document and know which option got selected, this is the css selector:

document.querySelector('#myDropdown > .dropdown-option.selectedOption')

 function myFunction() { var country = [ { "ID": "001", "Country_Name": "India" }, { "ID": "002", "Country_Name": "Australia" }, { "ID": "003", "Country_Name": "Austria" }, { "ID": "004", "Country_Name": "China" }, { "ID": "005", "Country_Name": "Bangladesh" } ]; document.getElementById("myDropdown").classList.toggle("show"); var ele = document.getElementById("myDropdown"); //for each country in the country array for (var i = 0; i < country.length; i++) { //creates an anchor element const countryOption = document.createElement("a"); //holding the country ID in its value attribute countryOption.setAttribute('value', country[i]['ID']); //and the country Name as its innerText countryOption.innerText = country[i]['Country_Name']; //adds the class dropdown-option to the option element countryOption.classList.add('dropdown-option'); //binds the countryOnClick function defined below as its click event handler countryOption.addEventListener('click', countryOnClick); //appends the new anchor to the dropdown element ele.appendChild(countryOption); } } //click event handler for the dropdown options function countryOnClick(event){ //fetch country properties from the element triggering the event const clickedOption = event.target; const countryID = clickedOption.getAttribute('value'); const countryName = clickedOption.innerText; //removes the selectedOption class to every option in the dropdown clickedOption.closest('div').querySelectorAll('.dropdown-option').forEach((o,i)=>{ o.classList.remove('selectedOption'); }); //adds the selectedOption class to the selected option element clickedOption.classList.add('selectedOption'); //show those data on console console.log(`${countryID} - ${countryName}`); console.log( getSelectedOption() ); } function getSelectedOption(){ return document.querySelector('#myDropdown > .dropdown-option.selectedOption'); } //gets called when the filter input changes, and it filters the dropdown options list 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"; } } }
 #myInput { box-sizing: border-box; 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; } position: relative; display: inline-block; } .dropdown-content { display: none; position: absolute; background-color: #f6f6f6; min-width: 230px; border: 1px solid #ddd; z-index: 1; } .dropdown-content a { color: black; padding: 12px 16px; text-decoration: none; display: block; } .dropdown-content a:hover { background-color: #f1f1f1 } .show { display: block; } .dropdown-content > .dropdown-option{ cursor: pointer; } .dropdown-content > .selectedOption{ background-color: darkgray !important; }
 <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()"> <a value=""></a> </div> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM