Select fields

Select fields are similar to radio buttons—they also allow the user to choose from a set of options. User can select any number of options rather than just a single option when given the multiple attribute. The size attribute to the <select> tag is used to set the number of options that are visible at the same time. For example, setting the size attribute to "3" will make the field show three lines, whether it has the multiple option enabled or not.

<select multiple>
<option>Pancakes</option>
<option>Pudding</option>
<option>Icecream</option>
</select>

Each <option> tag has a value. This value can be defined with a value attribute, but when that is not given, the text inside the option will count as the option's value. The value property of a <select> element reflects the currently selected option. For a multiple field, the property selected will give the value of only one of the currently selected options.

The <option> tags for a <select> field can be accessed as an array-like object through the field's options property. Each option has a property called selected, which indicates whether that option is currently selected. The property can also be written to select or deselect an option.

The following example extracts the selected values from a multiple select field and uses them to compose a binary number from individual bits. Hold Ctrl (or Command on a Mac) to select multiple options.

snippet
<select multiple>
<option value="1">0001</option>
<option value="2">0010</option>
<option value="4">0100</option>
<option value="8">1000</option>
</select>=<span id="output">0</span>

<script>
var select = document.querySelector("select");
var output = document.querySelector("#output");
select.addEventListener("change", function() {
    var number = 0;
    for (var i = 0; i & lt; select.options.length; i++) {
        var option = select.options[i];
        if (option.selected)
            number += Number(option.value);
    }
    output.textContent = number;
});
</script>
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents