0

Hello everybody I am currently working on a LWC form where I have some fields like inputs, comboboxes... In a combobox field when the user chooses, for instance the option A, an other lightning-input field, let's call it 'Item1' becomes required. But when the user chooses the option B from the combobox the Item1 field is not required.

Could anybody tell me how to indicate when the item1 field is required based on the combobox selection? Could someone put the code as an example? Thanks

1 Answer 1

0

Use a getter function on your component's controller that evaluates whether the selected combobox option was option A, and then on your input component, use the returned value from that function to set the requiredness of the input:

<template>
    <!-- this combobox will control the requiredness for the rest of components -->
    <lightning-combobox
            name="progress"
            label="Status"
            value={value}
            placeholder="Select Progress"
            options={options}
            onchange={handleChange} ></lightning-combobox>

    <!-- required property using the getter function -->
    <lightning-input type="text" label="Enter some text" required={isRequired}></lightning-input>
</template>

JS Controller:

import { LightningElement } from 'lwc';

export default class ComboboxBasic extends LightningElement {
    value = 'inProgress';

    get options() {
        return [
            { label: 'New', value: 'new' },
            { label: 'In Progress', value: 'inProgress' },
            { label: 'Finished', value: 'finished' },
        ];
    }

    handleChange(event) {
        this.value = event.detail.value;
    }

    // this function will mandate if the input should be required or not.
    get isRequired() {
        return this.value === 'finished';
    }
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .