Digital humanities


Maintained by: David J. Birnbaum (djbpitt@gmail.com) [Creative Commons BY-NC-SA 3.0 Unported License] Last modified: 2021-12-27T22:03:49+0000


JavaScript multiple selection feature

Working example

You chose:

HTML

Here is the HTML:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>Multiselect example</title>
        <link rel="stylesheet" type="text/css" href="http://www.obdurodon.org/css/style.css" />
    </head>
    <body>
        <h1>Dropdowns are the best!</h1>
        <select id="animal">
            <option>Cats</option>
            <option>Dogs</option>
            <option>Penguins</option>
        </select>
        <select id="quality">
            <option>are awesome!</option>
            <option>are creepy!</option>
            <option>are cute!</option>
        </select>
        <button>Continue</button>
        <p>You chose: <span id="output" style="background-color: pink;"></span></p>
    </body>
</html>

Our JavaScript needs to read the values of the two dropdowns (<select> elements with <option> child elements) and create output in a <span> that is initially empty. We assign @id attributes to each of those three elements so that we can refer to them easily in the JavaScript. Note that there is no inline JavaScript; except for single background-color specification on the output (invisible when the <span> is empty, as it is initially), the HTML document consists entirely of HTML content.

JavaScript

Here is the JavaScript that animates the selection tool:

function display() {
    var animal = document.getElementById("animal");
    var quality = document.getElementById("quality");
    document.getElementById("output").textContent = 
        animal.options[animal.selectedIndex].text +
        " " + 
        quality.options[quality.selectedIndex].text;
}
function init() {
    var button = document.getElementsByTagName('button')[0];
    button.addEventListener('click', display, false);
}
window.onload = init;

How it works

The window.onload = init; statement at the end causes the init() function to fire once the page has loaded completely.

The init() function attaches an event listener to the button. We set the variable button by rounding up a collection of all <button> elements in the document (there is only one) and then using the numerical index value of 0 to choose the first (zeroeth, in JavaScript terms, since JavaScript begins counting from zero) item in that collection. Even though there is only one <button> element, the JavaScript .getElementsByTagName() method always returns a collection, and you always need to use a numerical index value to select an item from the collection—even when there is only one item. We tell the event listener to listen for click events and to fire the display() function when the user clicks the button.

Inside the display() function: