search
HomeWeb Front-endFront-end Q&AHow to use JavaScript to implement drop-down box functionality

Preface

The drop-down box in the form is a commonly used interactive component, which can help users select the required options more quickly and conveniently. This article will demonstrate how to use JavaScript to implement drop-down box functionality.

HTML structure

We first need to create an HTML structure, including a <select></select> tag and multiple <option></option> tags. The <select></select> label represents the drop-down box container, the <option></option> label represents the options in the drop-down box, and the value attribute of each <option></option> label Represents the value of the option, and the content of the <option></option> tag represents the name of the option.

<select>
  <option>选项1</option>
  <option>选项2</option>
  <option>选项3</option>
  <option>选项4</option>
</select>

JavaScript implementation

In JavaScript, you can get the value of the currently selected option by getting the value attribute of the <select></select> tag. By getting the selectedIndex attribute of the <select></select> tag, you can get the index of the currently selected option.

var selectList = document.getElementById("selectList");

var selectedValue = selectList.value; // 获取当前选中选项的值
var selectedIndex = selectList.selectedIndex; // 获取当前选中选项的索引

In order to give the drop-down box a better experience, we need to use JavaScript to implement the optional state switching function of the drop-down box. You can simulate a drop-down box by adding an onclick event to the <select></select> tag, setting the size attribute of the <select></select> tag to an appropriate value and displaying all options. At the same time, you can use CSS styles to beautify the style of the drop-down box.

function toggleSelectList() {
  var selectList = document.getElementById("selectList");

  if (selectList.size === 1) {
    selectList.style.display = "block";
    selectList.size = selectList.options.length;
  } else {
    selectList.style.display = "none";
    selectList.size = 1;
  }
}
select {
  display: none; /* 隐藏下拉框 */
  width: 100%;
  padding: .5rem;
  font-size: 1rem;
  border: none;
  background-color: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  font-family: inherit;
}

Binding events

Finally, we need to bind the above JavaScript code with HTML structures and events. Here, we use the onchange event on the HTML tag and the custom toggleSelectList function to pop up and hide the drop-down box list.

<select>
    <option>选项1</option>
    <option>选项2</option>
    <option>选项3</option>
    <option>选项4</option>
</select>
function changeOption() {
  var selectList = document.getElementById("selectList");
  var selectedValue = selectList.value;
  console.log(selectedValue);
  toggleSelectList();
}

Complete code

HTML structure

<select>
    <option>选项1</option>
    <option>选项2</option>
    <option>选项3</option>
    <option>选项4</option>
</select>

JavaScript implementation

function toggleSelectList() {
  var selectList = document.getElementById("selectList");

  if (selectList.size === 1) {
    selectList.style.display = "block";
    selectList.size = selectList.options.length;
  } else {
    selectList.style.display = "none";
    selectList.size = 1;
  }
}

function changeOption() {
  var selectList = document.getElementById("selectList");
  var selectedValue = selectList.value;
  console.log(selectedValue);
  toggleSelectList();
}

CSS style

select {
  display: none; /* 隐藏下拉框 */
  width: 100%;
  padding: .5rem;
  font-size: 1rem;
  border: none;
  background-color: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  font-family: inherit;
}

Summary

Passed JavaScript implements drop-down boxes, which can make page interaction more friendly and convenient. Through studying this article, it is not difficult to find that the principle of implementing drop-down boxes in JavaScript is very simple. By obtaining the attribute value of the <select></select> tag, you can obtain the value of the drop-down box and switch the selected state. At the same time, JavaScript is required to pop up and hide the drop-down box list.

The above is the detailed content of How to use JavaScript to implement drop-down box functionality. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Mastering CSS Selectors: Class vs. ID for Efficient StylingMastering CSS Selectors: Class vs. ID for Efficient StylingMay 16, 2025 am 12:19 AM

The use of class selectors and ID selectors depends on the specific use case: 1) Class selectors are suitable for multi-element, reusable styles, and 2) ID selectors are suitable for unique elements and specific styles. Class selectors are more flexible, ID selectors are faster to process but may affect code maintenance.

HTML5 Specification: Exploring the Key Goals and MotivationsHTML5 Specification: Exploring the Key Goals and MotivationsMay 16, 2025 am 12:19 AM

ThekeygoalsandmotivationsbehindHTML5weretoenhancesemanticstructure,improvemultimediasupport,andensurebetterperformanceandcompatibilityacrossdevices,drivenbytheneedtoaddressHTML4'slimitationsandmeetmodernwebdemands.1)HTML5aimedtoimprovesemanticstructu

CSS IDs and Classes : a simple guideCSS IDs and Classes : a simple guideMay 16, 2025 am 12:18 AM

IDsareuniqueandusedforsingleelements,whileclassesarereusableformultipleelements.1)UseIDsforuniqueelementslikeaspecificheader.2)Useclassesforconsistentstylingacrossmultipleelementslikebuttons.3)BecautiouswithspecificityasIDsoverrideclasses.4)Useclasse

HTML5 Goals: Understanding the Key Objectives of the SpecificationHTML5 Goals: Understanding the Key Objectives of the SpecificationMay 16, 2025 am 12:16 AM

HTML5aimstoenhancewebaccessibility,interactivity,andefficiency.1)Itsupportsmultimediawithoutplugins,simplifyinguserexperience.2)Semanticmarkupimprovesstructureandaccessibility.3)Enhancedformhandlingincreasesusability.4)Thecanvaselementenablesdynamicg

Is it difficult to use HTML5 to achieve its goals?Is it difficult to use HTML5 to achieve its goals?May 16, 2025 am 12:06 AM

HTML5isnotparticularlydifficulttousebutrequiresunderstandingitsfeatures.1)Semanticelementslike,,,andimprovestructure,readability,SEO,andaccessibility.2)Multimediasupportviaandelementsenhancesuserexperiencewithoutplugins.3)Theelementenablesdynamic2Dgr

CSS: Can I use multiple IDs in the same DOM?CSS: Can I use multiple IDs in the same DOM?May 14, 2025 am 12:20 AM

No,youshouldn'tusemultipleIDsinthesameDOM.1)IDsmustbeuniqueperHTMLspecification,andusingduplicatescancauseinconsistentbrowserbehavior.2)Useclassesforstylingmultipleelements,attributeselectorsfortargetingbyattributes,anddescendantselectorsforstructure

The Aims of HTML5: Creating a More Powerful and Accessible WebThe Aims of HTML5: Creating a More Powerful and Accessible WebMay 14, 2025 am 12:18 AM

HTML5aimstoenhancewebcapabilities,makingitmoredynamic,interactive,andaccessible.1)Itsupportsmultimediaelementslikeand,eliminatingtheneedforplugins.2)Semanticelementsimproveaccessibilityandcodereadability.3)Featureslikeenablepowerful,responsivewebappl

Significant Goals of HTML5: Enhancing Web Development and User ExperienceSignificant Goals of HTML5: Enhancing Web Development and User ExperienceMay 14, 2025 am 12:18 AM

HTML5aimstoenhancewebdevelopmentanduserexperiencethroughsemanticstructure,multimediaintegration,andperformanceimprovements.1)Semanticelementslike,,,andimprovereadabilityandaccessibility.2)andtagsallowseamlessmultimediaembeddingwithoutplugins.3)Featur

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.