[SalesForce] How to read Lightning Checkbox toggle button value or checked status

We're using the toggle checkbox button as below.

<aura:attribute name="viewAllItemsSwitch" type="String" description="View all on/off" default="off"/>
                      <div class="slds-form-element">
                    <label class="slds-checkbox_toggle slds-grid">
                      <span class="slds-form-element__label slds-m-bottom_none">View All Items</span>
                      <input aura:id="swtichAllItems" type="checkbox" label="View All Items" value="{!v.viewAllItemsSwitch}" aria-describedby="toggle-desc" name="viewAllItems"  onchange="{!c.switchSelectItemsView}" class="slds-p-around_large"/>

                      <span id="toggle-desc" class="slds-checkbox_faux_container" aria-live="assertive">
                        <span class="slds-checkbox_faux"></span>
                        <span class="slds-checkbox_on">All Items displayed</span>
                        <span class="slds-checkbox_off">Some Items displayed</span>
                      </span>
                    </label>
                  </div>

I read the value or checked status inside the input–>onchange() as below.

        var toggleButton = component.find('swtichAllItems');
        if (toggleButton!=null)
            console.log(' value: '+toggleButton.get("v.value")+' checked: '+toggleButton.get("v.checked"));

It's not captured, and console.log as below.

value: undefined checked: undefined

Is it not correct? I need to get the value or checked status of the Lightning checkbox toggle.

Best Answer

If you're using a normal input, you need to get the element and then check its checked attribute:

logChange: function(component, event, helper) {
    console.log(component.find("someAuraId").getElement().checked);
}

If you're using ui:inputCheckbox or lightning:input type="toggle", and you need to know the value, consider binding to an attribute. Here's both types together:

<aura:attribute name="box1" type="Boolean" default="true" />
<aura:attribute name="box2" type="Boolean" default="true" />

<aura:handler name="change" value="{!v.box1}" action="{!c.logChange1}" />
<aura:handler name="change" value="{!v.box2}" action="{!c.logChange2}" />

<ui:inputCheckbox value="{!v.box1}" label="The Box To Check" />
<lightning:input name="box2" type="toggle" checked="{!v.box2}" label="The Other Box To Check" />

logChange1: function(component, event, helper) {
    console.log(component.get("v.box1"));
},
logChange2: function(component, event, helper) {
    console.log(component.get("v.box2"));
},