🔬 Welcome to STEMFACT

Science | Experiments | Numericals | Games

Wednesday, 23 October 2024

Accessing elements from drop-down in javascript code With Example

Accessing Elements from Drop-Down Menus in JavaScript

Question:

How can you access the selected value from a drop-down menu (<select> element) in JavaScript?

Options:

  • 1. element.value
  • 2. element.selectedIndex
  • 3. element.options[element.selectedIndex].text
  • 4. All of the above

Answer: 4. All of the above

Explanation:

  • element.value: Returns the selected value of the drop-down menu.
  • element.selectedIndex: Returns the index of the selected option (starting from 0).
  • element.options[element.selectedIndex].text: Returns the text of the selected option.

Example 1: Accessing Values from Drop-Down Menu

<select id="mySelect">
  <option value="option1">Option 1</option>
  <option value="option2">Option 2</option>
  <option value="option3">Option 3</option>
</select>

<script>
  const select_Element = document.getElementById("mySelect");

  // Accessing the selected value
  const selectedValue = select_Element.value;
  console.log("Selected value:", selectedValue);

  // Accessing the selected index
  const selectedIndex = select_Element.selectedIndex;
  console.log("Selected index:", selectedIndex);

  // Accessing the selected option's text
  const selectedText = select_Element.options[selectedIndex].text;
  console.log("Selected text:", selectedText);
</script>

Example 2: Actress Drop-Down Menu

<select id="actressSelect">
  <option value="option1">Actress 1</option>
  <option value="option2">Actress 2</option>
  <option value="option3">Actress 3</option>
</select>

<button onclick="getActress()">Get Actress</button>

<script>
function getActress() {
  const actressSelect = document.getElementById("actressSelect");
  const selectedActress = actressSelect.options[actressSelect.selectedIndex].text;

  // Display selected actress in a message
  alert("You selected: " + selectedActress);
}
</script>

Explanation:

- Create a <select> element with the id="actressSelect".
- Add options for different actresses.
- Create a button that calls the getActress() function when clicked.
- In JavaScript, use document.getElementById("actressSelect") to get the element.
- Access the selected actress using actressSelect.options[actressSelect.selectedIndex].text.
- Display it in an alert message.

Usage:

  • Open the HTML file in a web browser.
  • Select an actress from the drop-down menu.
  • Click the "Get Actress" button.
  • The selected actress will be displayed in an alert message.

No comments:

Post a Comment

Aufbau, Pauli's , Hund's Rule

Aufbau, Hund's Rule & Pauli Exclusion Principle Aufbau Principle, Hund’s Rule & Pauli Exclusion Principle Visual...