javascripthtmljquerycssonsen-ui

How to get multiple checkbox value on button click from an Onsen Checkbox?


I am using ons-checkbox provided by Onsen-UI, I have multiple checbox

<ons-checkbox input-id = "brand" value = "example" class = "checkbox"></ons-checkbox>

on the button click I want to get the values of all the checked checkboxes


Solution

  • checkbox.html

    <ons-page>
      <div style="text-align: center; margin-top: 30px;">
        <p style="margin-top: 30px;">
          <ons-button onclick="checkedData()">Data</ons-button>
        </p>
        <ons-list>
        <ons-list-item tappable>
          <label class="left">
            <ons-checkbox input-id="check-1" value="Apple"></ons-checkbox>
          </label>
          <label for="check-1" class="center">
            Apple
          </label>
        </ons-list-item>
        <ons-list-item tappable>
          <label class="left">
            <ons-checkbox input-id="check-2" value="Banana"></ons-checkbox>
          </label>
          <label for="check-2" class="center">
            Banana
          </label>
        </ons-list-item>
      </ons-list>
    
      </div>
    </ons-page>
    

    checkbox.js

    var checkedData = function() {
      var ons = document.getElementsByTagName('ons-checkbox');
      for (var i=0; i<ons.length; i++) {
        if(ons[i].checked) {
          // Below will give all checked values
          console.log('Checked Values : , ons[i].value);
        } else {
          // Below will give all un-checked values
          console.log('Un-Checked Values : , ons[i].value);
        }
      }
    };