settingsAccountsettings
Menusettings

Q: Fill Dropdown Task in HTML with DOM and JavaScript

+2 votes

Your task is to take values from input fields with id’s “newItemText” and “newItemValue” and create and append an <option> to the <select> with id “menu”.

HTML and JavaScript Code - You are given the following HTML code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Fill Dropdown</title>
    <script src="dropdown.js"></script>
</head>
<body>
<h1>Dropdown Menu</h1>
<div>
    <select id="menu"></select>
</div>
  <label for="newItemText">Text: </label><input type="text" id="newItemText" />
  <label for="newItemValue">Value: </label><input type="text" id="newItemValue" />
  <input type="button" value="Add" onclick="addItem()">
</body>
</html>
  • Your function should take the values of newItemText and newItemValue. After that you should create a new option element and set it’s textContent and it’s value to the newly taken ones.
  • Once you have done all of that you should append the newly created option as a child to the select item with id “menu”.
  • Finally you should clear the value of the two input fields.

Examples:

dropdown menu javascript

asked in JavaScript category by user andrew

1 Answer

+1 vote

Here is my solution - with HTML and the JavaScript code inside:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Fill Dropdown</title>
</head>
<body>
<h1>Dropdown Menu</h1>

<div>
    <select id="menu"></select>
</div>
<label for="newItemText">Text: </label><input type="text" id="newItemText"/>
<label for="newItemValue">Value: </label><input type="text" id="newItemValue"/>
<input type="button" value="Add" onclick="addItem()">

<script>
    function addItem() {
        let inputText = document.getElementById("newItemText");
        let inputValue = document.getElementById("newItemValue");
        let option = document.createElement("option");
        option.value = inputValue.value;
        option.textContent = inputText.value;
        document.getElementById("menu").appendChild(option);
        inputText.value = "";
        inputValue.value = "";
    }
</script>
</body>
</html>

 

answered by user eiorgert
...