samedi 21 novembre 2020

How to enable/disable the input box using checkbox?

I have a component in which I have two sections one contains checkboxes and other contains input field(input field are inside a form).

I am looking for a solution, if anyone check the checkbox then only the related inbox field should be enabled and else should be disabled and if some uncheck a checkbox then that field should disabled.

for example if someone checked the Tom checkbox then only the Tom input field be enabled and other than Tom should be disable and if some one uncheck the Tom(checkbox) then it should be disabled again.

import React from "react";
import Card from '@material-ui/core/Card';
import './cardinput.css'
import Checkbox from '@material-ui/core/Checkbox';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import TextField from '@material-ui/core/TextField';
import { Button } from "@material-ui/core";


export default function App() {

    const [checked, setChecked] = React.useState(true);
    const [inputDisabled, setInputDisabled] = React.useState(true);
    
    const handleChange = (event) => {
      setChecked(event.target.checked);
    };

    const handleSubmit = (event) => {
        event.preventDefault();
    }

    const person = [
        {label:"Tom"},
        {label:"Jerry"},
        {label:"Cat"},
        {label:"Mouse"},
    ]

  return (
    <React.Fragment>
      <Card className="main-card">  
        <div className="checkbox-card">
            {
                person.map((item, key) => (
                    <React.Fragment>
                        <FormControlLabel
                        value="Tom"
                        control={<Checkbox color="primary" />}
                        label={item.label}
                        labelPlacement="end"
                        onChange={handleChange}
                        />
                    </React.Fragment>
                ))
            }
        </div>
        
        <div className="input-card-wrapper">
            <form  className="input-card" onSubmit={handleSubmit}>
                {
                    person.map((item,key) => (
                        <React.Fragment>
                            <TextField disabled={inputDisabled} label={item.label} variant="outlined" />
                        </React.Fragment>
                    ))
                }
                <Button variant="contained" color="primary">Submit</Button>
            </form>
        </div>
      </Card>
    </React.Fragment>
  );
}

Looking for a solution to enable and disable the input field with respect to checkbox.

Adding screen shot for better understanding Note: I am using the material design.




Aucun commentaire:

Enregistrer un commentaire