Tuesday, December 29, 2020

Get selected checkbox value in LWC

This post explains how to get selected checkbox values in LWC (Multiple Checkbox). Below is demo of output :

Get checkbox value LWC

GetCheckboxValue.html :


<template>
    <template for:each={data} for:item="option">
        <lightning-input
            style="padding : 10px; font-weight : bold;"
            data-id="checkbox" 
            class="slds-p-left_large"
            key={option} 
            label={option} 
            type="checkbox" 
            value={option} 
            onchange={handleChangeCheck}>
        </lightning-input>
    </template>
</template>

GetCheckboxValue.js


import { LightningElement,track,api } from 'lwc';

export default class GetCheckboxValue extends LightningElement {
    data = ['India', 'China', 'Japan', 'America', 'Russia'];
    @track index;
    @track Values;
    @track SelectedValues = [];

    handleChangeCheck(event) {      
        this.Values =  event.target.value;
        if (event.target.checked) {
            this.SelectedValues.push( this.Values);
        } else {
            try {
                this.index = this.SelectedValues.indexOf( this.Values);
                this.SelectedValues.splice(this.index, 1);
            } catch (err) {
                //error message
            }
        }
        alert('selected checkbox are : '+JSON.stringify(this.SelectedValues));
    }
}

GetCheckboxValue.Meta


<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>45.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
    </targets>
</LightningComponentBundle>

Output :


Get checkbox value LWC

Thanks, 
Lovesalesforceyes


No comments:

Post a Comment

Get selected radio button value in LWC

This post explains how to get selected radio button in LWC. Below is demo of output : To use the radio button in LWC you have to use the  li...