Udostępnij za pośrednictwem


Quickstart: Adding checkbox controls (HTML)

[ This article is for Windows 8.x and Windows Phone 8.x developers writing Windows Runtime apps. If you’re developing for Windows 10, see the latest documentation ]

Learn how to create checkbox controls. Use check boxes to present users with a binary choice, one or more options that are not mutually exclusive, or a mixed choice.

Prerequisites

Create a checkbox

To create a checkbox, you create an input element and set its type attribute to "checkbox". You add your text for the checkbox after the input element's closing tag.

Tip  When you add a checkbox, enclose it in a label element to increase the size of the area that responds to user interaction. Doing so makes it easier to use the checkbox on touch devices.

 

By default, a checkbox is clear, or unchecked, until the user clicks it. To make a checkbox start off as selected, or checked, use the checked attribute. This example creates four checkbox controls and uses the checked attribute to make the second one checked.


.controlGroup
{
    margin: 0px 0px 20px 0px;
    padding: 0px;
    border: 0px;
}

.controlGroupName
{
    font:normal normal normal 11pt/15pt "Segoe UI Semilight";
    font-size: 11pt; 
    margin:0px 0px 10px 0px;
    padding:0px;
    border: 0px;
    position:relative;
    vertical-align:top;
    display:block;
}

.verticalStacking input[type="checkbox"]
{
    margin-bottom: 16px;
}
<div style="margin: 20px">
<fieldset class="controlGroup verticalStacking">
    <legend class="controlGroupName">Choose an option:</legend>
    <label>
        <input id="option1" type="checkbox" class="checkboxExample1"  />Option 1
    </label>
    <br />
    <label>
        <input id="option2" type="checkbox" class="checkboxExample1" checked />Option 2
    </label>
    <br />
    <label>
        <input id="option3" type="checkbox" class="checkboxExample1" />Option 3
    </label>
    <br />
    <label>
        <input id="option4" type="checkbox" class="checkboxExample1" />Option 4
    </label>
    </fieldset>
</div>

When you run the code, option 1, 3, and 4 are unchecked, but option 2 is checked.

Four checkboxes

Determine whether a checkbox is checked

The checkbox supports the same events as other input elements, including the click event. However, the checkbox is intended for status information and usually doesn't trigger an action (except in the case of an indeterminate checkbox, which we talk about in the next section). Rather than handling the checkbox's click event and immediately performing an action based on the checkbox's checked state, you usually read checkbox state when the user clicks some sort of "submit" button to commit a set of options. (If you want to perform an action, use a ToggleSwitch control instead.)

To determine whether a checkbox is checked, use its checked property. This example creates a button that displays the checked values of the checkbox controls created in the previous example.

function evaluateCheckboxState(eventInfo) {
    var outputDiv = document.getElementById("checkedStateOutput");
    var output = "<ul>";
    WinJS.Utilities.query(".checkboxExample1").forEach(function (checkbox) {
        output += "<li>" + checkbox.id + " checked: " + checkbox.checked + "</li>"; 
    }); 
    outputDiv.innerHTML = output + "</ul>"; 

}

WinJS.Namespace.define("CheckboxExamples",
    { evaluateCheckboxState: evaluateCheckboxState });

Here's what it looks like when you run the code and click the button:

Four checkboxes

Create an indeterminate checkbox

When an option applies to more than one object, you can use a checkbox to indicate whether the option applies to all, some, or none of those objects. When the option applies to some, but not all, of those objects, use the checkbox's indeterminate state to represent a mixed choice.

You can set the indeterminate property only in JavaScript—there is no "indeterminate" attribute that you can set in HTML.

Note  Changing a checkbox's indeterminate property does not automatically change its checked value.

 

This example creates a "Select all" checkbox that checks or unchecks a set of child checkbox controls (options 1-4).

<fieldset class="controlGroup verticalStacking">
    <legend class="controlGroupName">Choose an option:</legend>

    <label>
        <input type="checkbox" id="selectAll" onclick="CheckboxExamples.checkAll(event)" />Select all
    </label>
    <div style="margin-left: 29px" onclick="CheckboxExamples.updateCheckboxes(event)">
        <label>
            <input id="Checkbox1" type="checkbox" class="checkboxExample2"  />Option 1
        </label>
        <br />
        <label>
            <input id="Checkbox2" type="checkbox" class="checkboxExample2" checked />Option 2
        </label>
        <br />
        <label>
            <input id="Checkbox3" type="checkbox" class="checkboxExample2" />Option 3
        </label>
        <br />
        <label>
            <input id="Checkbox4" type="checkbox" class="checkboxExample2" />Option 4
        </label>
    </div>

</fieldset>

Here's what the checkbox controls look like:

A checkbox in the indeterminate state

The example handles the selectAll checkbox's click event so that clicking it triggers the checkAll function.

<input type="checkbox" id="selectAll" onclick="CheckboxExamples.checkAll(event)" />Select all

The checkAll function checks or unchecks all the other checkbox controls when you check or uncheck the selectAll checkbox.

function checkAll(eventInfo) {

    var options = document.getElementsByClassName("checkboxExample2");
    for (var i = 0; i < options.length; i++) {
        options[i].checked = event.srcElement.checked;
    }
}

The updateCheckboxes function is called when any of the child checkbox controls are clicked.

<div style="margin-left: 29px" onclick="CheckboxExamples.updateCheckboxes(event)">

It finds out the checked state of each checkbox and updates the selectAll checkbox.

  • If every child checkbox is checked, it sets the selectAll checkbox's indeterminate state to false and its checked value to true.
  • If every child checkbox is unchecked, it sets the selectAll checkbox's indeterminate state to false and its checked value to false.
  • If some child checkbox controls are checked and others are unchecked, it sets the selectAll checkbox's indeterminate state to true and its checked value to false.
function updateCheckboxes(eventInfo) {
    var options = document.getElementsByClassName("checkboxExample2");
    var selectedCount = 0;
    for (var i = 0; i < options.length; i++) {
        if (options[i].checked) {
            selectedCount++;
        }
    }

    // Update the selectAll checkbox
    // to reflect the state of the child checkboxes.
    var selectAll = document.getElementById("selectAll"); 
    if (options.length === selectedCount) {
        selectAll.indeterminate = false;
        selectAll.checked = true;
    } else if (0 === selectedCount) {
        selectAll.indeterminate = false;
        selectAll.checked = false;
    } else {
        selectAll.indeterminate = true;
        //selectAll.checked = false;
    }
}

The next part of the example uses WinJS.Namespace.define to make checkAll and updateCheckboxes public.

WinJS.Namespace.define("CheckboxExamples",
    {
        checkAll: checkAll,
        updateCheckboxes: updateCheckboxes
    });

There's one more thing to do here. The second option starts off in the checked state:

<label>
    <input id="Checkbox2" type="checkbox" class="checkboxExample2" checked />Option 2
</label>

The selectAll checkbox starts off in the clear, or "unchecked", state, and the updateCheckboxes method doesn't get called until the user clicks a checkbox. So, when the example code runs, the selectAll checkbox is unchecked when it should be in the indeterminate state:

The select all checkbox should be in the indeterminate state

To fix the issue, add a call to updateCheckboxes when the page loads.

  • If your code is in a PageControl, use the ready method to call updateCheckboxes.
  • If your code is in your app's default.js file, use the activated event handler to call updateCheckboxes.
  • In either case, you can also handle the DOMContentLoaded event and use the handler to call updateCheckboxes.

This example uses a PageControl, so it calls updateCheckboxes from the ready method.

WinJS.UI.Pages.define("/pages/checkbox/checkbox.html", {
    // This function is called whenever a user navigates to this page. It
    // populates the page elements with the app's data.
    ready: function (element, options) {
        // TODO: Initialize the page here.

        CheckboxExamples.updateCheckboxes(); 
    },

    unload: function () {
        // TODO: Respond to navigations away from this page.
    },

    updateLayout: function (element, viewState, lastViewState) {
        /// <param name="element" domElement="true" />

        // TODO: Respond to changes in viewState.
    }
});

Summary and next steps

You learned how to create checkbox controls, how to find out their state, and how to use the indeterminate property to indicate an in-between state.

Next, have a look at How to style checkbox controls.

How to style checkbox controls

Guidelines and checklist for checkbox controls