w3resource

JavaScript: Count and display the items of a dropdown list, in an alert window

JavaScript DOM: Exercise-9 with Solution

Write a JavaScript program to count and display the items of a dropdown list in an alert window.

Sample Solution:

HTML Code:

<!-- Declaration of HTML document type -->
<!doctype html>
<!-- Start of HTML document -->
<html lang="en">
<head>
<!-- Declaring character encoding -->
<meta charset="utf-8">
<!-- Setting title of the document -->
<title>Volume of a Sphere</title>
<!-- Internal CSS styling -->
<style>  
    /* Styling body to have padding at the top */
    body{padding-top:30px;}
    /* Styling label and input elements to display as block */
    label,input{display:block;}  
</style>
</head>
<!-- Start of body section -->
<body>
<!-- Paragraph explaining the purpose of the form -->
<p>Input radius value and get the volume of a sphere.</p>
<!-- Form for inputting radius and displaying volume -->
<form action="" method="post" id="MyForm">
    <!-- Label and input field for entering radius -->
    <label for="radius">Radius</label><input type="text" name="radius" id="radius" required>
    <!-- Label and input field for displaying volume -->
    <label for="volume">Volume</label><input type="text" name="volume" id="volume">
    <!-- Submit button for calculating volume -->
    <input type="submit" value="Calculate" id="submit">
</form>
<!-- End of body section -->
</body>
<!-- End of HTML document -->
</html>

JavaScript Code:

// Function declaration for getOptions
function getOptions()
{
    // Getting reference to the select element with id 'mySelect'
    var x=document.getElementById("mySelect");
    // Initializing text variable to hold the message
    var txt1 = "No. of items : ";
    var i;
    // Getting the length of the select element
    l=document.getElementById("mySelect").length;  
    // Concatenating the length of the select element to the message
    txt1 = txt1+l;
    // Looping through each option in the select element
    for (i=0;i<x.length;i++)
    {
        // Concatenating each option's text to the message with a newline character
        txt1 = txt1 + "\n" + x.options[i].text;
    }
    // Displaying the message in an alert dialog
    alert(txt1);
}

Output:

javascript-dom-exercise-9.

Flowchart:

Flowchart: JavaScript - Count and display the items of a dropdown list, in an alert window.

Live Demo:

See the Pen javascript-dom-exercise-9 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus.

Previous: Write a JavaScript program to remove items from a dropdown list.
Next: Write a JavaScript program to calculate the volume of a sphere.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.