如何仅禁用使用复选框的输入字段?

发布于 2025-02-13 07:48:20 字数 3634 浏览 1 评论 0原文

我想使用复选框禁用“完成日期”字段。

问题是我动态创建了这些字段,因此,当我尝试仅禁用与之相关的字段时,它会禁用所有其他“完成日期”字段,我希望仅禁用上一个字段,而不是所有其他字段。

image

    const [checked, setChecked] = useState(false)    
    const [inputList, setInputList] = useState([
        { 
            startDate: "Start Date",            
            completionDate: "Completion Date:",
            inline: true 
        }
    ])
    const handleInputChange = (e, index, val) => {
        const { name, value } = e.target
        setChecked(e.target.checked)    
    
        const list = [...inputList]
    
        list[index][name] = val !== undefined ? val : value 
        setInputList(list)
    }
    const handleRemoveClick = (index) => {
        const list = [...inputList]
        list.splice(index, 1)
        setInputList(list)
    }
    const handleAddClick = () => {
        setInputList([
            ...inputList,
            { 
                startDate: "Start Date",            
                completionDate: "Completion Date:",
                inline: true 
            }
        ])
    }
    let embed = {
        embed: {
            fields: inputList
        }
    }    
    //Form
    {inputList.map((x, i) => {                
        return (
            <>           
                <FormControl>
                    <Box>
                        <FormLabel htmlFor='startDate'>Start Date:</FormLabel>                      
                        <Input 
                            name="startDate"
                            onChange={(e) => handleInputChange(e, i)}              
                            type='text' 
                            placeholder='Start Date' 
                        />                                                
                    </Box>
                    <Box>
                        <FormLabel htmlFor='completionDate'>Completion Date:</FormLabel>                        
                        <Input 
                            name="completionDate"
                            isDisabled={checked ? true : false}
                            onChange={(e) => handleInputChange(e, i)} 
                            type='text' 
                            placeholder='Completion Date' 
                        />                                                
                    </Box>                
                    <Box pt={{ base: '0', md: '2.7rem'}}>                       
                        <Checkbox  
                            type="checkbox" 
                            name="inline" 
                            checked={x.inline}                                     
                            onChange={(e) => handleInputChange(e, i, e.target.checked)}
                            colorScheme='purple'>
                                <label>Studying</label>
                        </Checkbox>  
                    </Box>                                 
                </FormControl>           
                {inputList.length - 1 === i && (
                    <Button onClick={handleAddClick}> + New Section </Button> 
                    )}
                {inputList.length !== 1 && (
                    <Button  onClick={() => handleRemoveClick(i)}>- Remove Section</Button> 
                )}                      
              
            </>
        )
    })} 

I would like to disable the "Date of Completion" field with the checkbox.

The problem is that I created these fields dynamically, so when I try to disable only the field relating to it, it disables all other "Date of Completion" fields I would like to disable only the previous field and not all others.

Image

    const [checked, setChecked] = useState(false)    
    const [inputList, setInputList] = useState([
        { 
            startDate: "Start Date",            
            completionDate: "Completion Date:",
            inline: true 
        }
    ])
    const handleInputChange = (e, index, val) => {
        const { name, value } = e.target
        setChecked(e.target.checked)    
    
        const list = [...inputList]
    
        list[index][name] = val !== undefined ? val : value 
        setInputList(list)
    }
    const handleRemoveClick = (index) => {
        const list = [...inputList]
        list.splice(index, 1)
        setInputList(list)
    }
    const handleAddClick = () => {
        setInputList([
            ...inputList,
            { 
                startDate: "Start Date",            
                completionDate: "Completion Date:",
                inline: true 
            }
        ])
    }
    let embed = {
        embed: {
            fields: inputList
        }
    }    
    //Form
    {inputList.map((x, i) => {                
        return (
            <>           
                <FormControl>
                    <Box>
                        <FormLabel htmlFor='startDate'>Start Date:</FormLabel>                      
                        <Input 
                            name="startDate"
                            onChange={(e) => handleInputChange(e, i)}              
                            type='text' 
                            placeholder='Start Date' 
                        />                                                
                    </Box>
                    <Box>
                        <FormLabel htmlFor='completionDate'>Completion Date:</FormLabel>                        
                        <Input 
                            name="completionDate"
                            isDisabled={checked ? true : false}
                            onChange={(e) => handleInputChange(e, i)} 
                            type='text' 
                            placeholder='Completion Date' 
                        />                                                
                    </Box>                
                    <Box pt={{ base: '0', md: '2.7rem'}}>                       
                        <Checkbox  
                            type="checkbox" 
                            name="inline" 
                            checked={x.inline}                                     
                            onChange={(e) => handleInputChange(e, i, e.target.checked)}
                            colorScheme='purple'>
                                <label>Studying</label>
                        </Checkbox>  
                    </Box>                                 
                </FormControl>           
                {inputList.length - 1 === i && (
                    <Button onClick={handleAddClick}> + New Section </Button> 
                    )}
                {inputList.length !== 1 && (
                    <Button  onClick={() => handleRemoveClick(i)}>- Remove Section</Button> 
                )}                      
              
            </>
        )
    })} 

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

沩ん囻菔务 2025-02-20 07:48:21

您应该将检查添加到inputList对象。

const [inputList, setInputList] = useState([
    {
        startDate: "Start Date",
        completionDate: "Completion Date:",
        inline: true,
        checked: false
    }
])
const handleInputChange = (e, index, val) => {
    const { name, value } = e.target

    let newList = inputList
    newList[index]['checked'] = e.target.checked
    setInputList(newList)

    const list = [...inputList]

    list[index][name] = val !== undefined ? val : value
    setInputList(list)
}
const handleRemoveClick = (index) => {
    const list = [...inputList]
    list.splice(index, 1)
    setInputList(list)
}
const handleAddClick = () => {
    setInputList([
        ...inputList,
        {
            startDate: "Start Date",
            completionDate: "Completion Date:",
            inline: true,
            checked: false
        }
    ])
}
let embed = {
    embed: {
        fields: inputList
    }
}
//Form
{
    inputList.map((x, i) => {
        return (
            <>
                <FormControl>
                    <Box>
                        <FormLabel htmlFor='startDate'>Start Date:</FormLabel>
                        <Input
                            name="startDate"
                            onChange={(e) => handleInputChange(e, i)}
                            type='text'
                            placeholder='Start Date'
                        />
                    </Box>
                    <Box>
                        <FormLabel htmlFor='completionDate'>Completion Date:</FormLabel>
                        <Input
                            name="completionDate"
                            isDisabled={x.checked}
                            onChange={(e) => handleInputChange(e, i)}
                            type='text'
                            placeholder='Completion Date'
                        />
                    </Box>
                    <Box pt={{ base: '0', md: '2.7rem' }}>
                        <Checkbox
                            type="checkbox"
                            name="inline"
                            checked={x.inline}
                            onChange={(e) => handleInputChange(e, i, e.target.checked)}
                            colorScheme='purple'>
                            <label>Studying</label>
                        </Checkbox>
                    </Box>
                </FormControl>
                {inputList.length - 1 === i && (
                    <Button onClick={handleAddClick}> + New Section </Button>
                )}
                {inputList.length !== 1 && (
                    <Button onClick={() => handleRemoveClick(i)}>- Remove Section</Button>
                )}

            </>
        )
    })
} 

You should add checked to inputList object.

const [inputList, setInputList] = useState([
    {
        startDate: "Start Date",
        completionDate: "Completion Date:",
        inline: true,
        checked: false
    }
])
const handleInputChange = (e, index, val) => {
    const { name, value } = e.target

    let newList = inputList
    newList[index]['checked'] = e.target.checked
    setInputList(newList)

    const list = [...inputList]

    list[index][name] = val !== undefined ? val : value
    setInputList(list)
}
const handleRemoveClick = (index) => {
    const list = [...inputList]
    list.splice(index, 1)
    setInputList(list)
}
const handleAddClick = () => {
    setInputList([
        ...inputList,
        {
            startDate: "Start Date",
            completionDate: "Completion Date:",
            inline: true,
            checked: false
        }
    ])
}
let embed = {
    embed: {
        fields: inputList
    }
}
//Form
{
    inputList.map((x, i) => {
        return (
            <>
                <FormControl>
                    <Box>
                        <FormLabel htmlFor='startDate'>Start Date:</FormLabel>
                        <Input
                            name="startDate"
                            onChange={(e) => handleInputChange(e, i)}
                            type='text'
                            placeholder='Start Date'
                        />
                    </Box>
                    <Box>
                        <FormLabel htmlFor='completionDate'>Completion Date:</FormLabel>
                        <Input
                            name="completionDate"
                            isDisabled={x.checked}
                            onChange={(e) => handleInputChange(e, i)}
                            type='text'
                            placeholder='Completion Date'
                        />
                    </Box>
                    <Box pt={{ base: '0', md: '2.7rem' }}>
                        <Checkbox
                            type="checkbox"
                            name="inline"
                            checked={x.inline}
                            onChange={(e) => handleInputChange(e, i, e.target.checked)}
                            colorScheme='purple'>
                            <label>Studying</label>
                        </Checkbox>
                    </Box>
                </FormControl>
                {inputList.length - 1 === i && (
                    <Button onClick={handleAddClick}> + New Section </Button>
                )}
                {inputList.length !== 1 && (
                    <Button onClick={() => handleRemoveClick(i)}>- Remove Section</Button>
                )}

            </>
        )
    })
} 
拥抱没勇气 2025-02-20 07:48:21

您的完成日期输入ISDISABLED属性取决于一个检查状态,该状态与所有完成日期输入共享。

<Input 
    name="completionDate"
    isDisabled={checked ? true : false}       //  <--- checked shared state
    ...
/> 

因此,当您单击任何复选框时,检查状态将通过handle InputChange更新,并且所有完成日期输入将处于禁用/启用模式,具体取决于最新的单击复选框检查值。

@hossein ,您需要添加检查属性。所以,让我们去做吧。

首先,更新您的inputList初始化:

  const [inputList, setInputList] = useState([
    {
      startDate: undefined,           // to hold startDate value
      completionDate: undefined,      // to hold completionDate value
      disabled: false,                // to hold completionDate disabled state
      checked: false,                 // to hold inline checked state
    },
  ]);

下一步,更新handleinputChange方法:

  const handleInputChange = (e, i) => {
    const { checked, name, value } = e.target;
    setInputList((prevState) => {
      if (name === "inline") {
        prevState[i].checked = checked;
        prevState[i].disabled = checked;  // disabled value follows checked value
      } else {
        prevState[i][name] = value;
      }
      return [...prevState];
    });
  };

更新您的handleaddclick方法:

  const handleAddClick = () => {
    setInputList((prevState) => {
      const newInputs = {
        startDate: undefined,
        completionDate: undefined,
        disabled: false,
        checked: false,
      };
      return [...prevState, newInputs];
    });
  };

下一步,在复选框中 和最后,更新您的onChange组件:

// from
onChange={(e) => handleInputChange(e, i, e.target.checked)}
// into
onChange={(e) => handleInputChange(e, i)}

进行这些更新后,您的代码应起作用。

这是有效的最小示例:

const { useState } = React;

function App() {
    const [inputList, setInputList] = useState([
        {
        startDate: undefined,
        completionDate: undefined,
        disabled: false,
        checked: false,
        },
    ]);

    const handleInputChange = (e, i) => {
        const { checked, name, value } = e.target;
        setInputList((prevState) => {
        if (name === "inline") {
            prevState[i].checked = checked;
            prevState[i].disabled = checked;
        } else {
            prevState[i][name] = value;
        }
        return [...prevState];
        });
    };

    const handleAddClick = () => {
        setInputList((prevState) => {
        const newInputs = {
            startDate: undefined,
            completionDate: undefined,
            disabled: false,
            checked: false,
        };
        return [...prevState, newInputs];
        });
    };

    const handleRemoveClick = (index) => {
        const list = [...inputList];
        list.splice(index, 1);
        setInputList(list);
    };

    return (
        <div>
            <div>App</div>
            {inputList.map((input, i) => {
                return (
                <div key={i}>
                    <br />
                    <div>
                    <label>
                        Start Date:
                        <input
                        name="startDate"
                        type="text"
                        onChange={(e) => handleInputChange(e, i)}
                        placeholder="Start Date"
                        />
                    </label>
                    </div>
                    <div>
                    <label>
                        Completion Date:
                        <input
                        name="completionDate"
                        type="text"
                        disabled={input.disabled}
                        onChange={(e) => handleInputChange(e, i)}
                        placeholder="Completion Date"
                        />
                    </label>
                    </div>
                    <div>
                    <label htmlFor={`checkbox-${i}`} style={{ cursor: "pointer" }}>
                        <input
                        id={`checkbox-${i}`}
                        name="inline"
                        type="checkbox"
                        checked={input.checked}
                        onChange={(e) => handleInputChange(e, i)}
                        />
                        {`Checkbox-${i}`}
                    </label>
                    </div>
                    <br />
                    {inputList.length - 1 === i && (
                    <button onClick={() => handleAddClick()}>+ New Section</button>
                    )}
                    {inputList.length !== 1 && (
                        <button onClick={() => handleRemoveClick(i)}>
                            - Remove Section
                        </button>
                    )}
                </div>
                );
            })}
        </div>
    );
}

ReactDOM.render(<App />, document.querySelector('.react'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div class='react'></div>

Your completion date input isDisabled property depends on one checked state which is shared with all completion date input.

<Input 
    name="completionDate"
    isDisabled={checked ? true : false}       //  <--- checked shared state
    ...
/> 

So, when you click any checkbox, the checked state will be updated by handleInputChange and all completion date input will be in disabled/enabled mode, depending on the latest clicked checkbox checked value.

As said by @hossein, you need to add checked property. So, let's do it.

First, update your inputList initialization:

  const [inputList, setInputList] = useState([
    {
      startDate: undefined,           // to hold startDate value
      completionDate: undefined,      // to hold completionDate value
      disabled: false,                // to hold completionDate disabled state
      checked: false,                 // to hold inline checked state
    },
  ]);

Next, update your handleInputChange method:

  const handleInputChange = (e, i) => {
    const { checked, name, value } = e.target;
    setInputList((prevState) => {
      if (name === "inline") {
        prevState[i].checked = checked;
        prevState[i].disabled = checked;  // disabled value follows checked value
      } else {
        prevState[i][name] = value;
      }
      return [...prevState];
    });
  };

Next, update your handleAddClick method:

  const handleAddClick = () => {
    setInputList((prevState) => {
      const newInputs = {
        startDate: undefined,
        completionDate: undefined,
        disabled: false,
        checked: false,
      };
      return [...prevState, newInputs];
    });
  };

And finally, update your onChange at Checkbox component:

// from
onChange={(e) => handleInputChange(e, i, e.target.checked)}
// into
onChange={(e) => handleInputChange(e, i)}

Your code should work after you made those updates.

Here is the minimal example that works:

const { useState } = React;

function App() {
    const [inputList, setInputList] = useState([
        {
        startDate: undefined,
        completionDate: undefined,
        disabled: false,
        checked: false,
        },
    ]);

    const handleInputChange = (e, i) => {
        const { checked, name, value } = e.target;
        setInputList((prevState) => {
        if (name === "inline") {
            prevState[i].checked = checked;
            prevState[i].disabled = checked;
        } else {
            prevState[i][name] = value;
        }
        return [...prevState];
        });
    };

    const handleAddClick = () => {
        setInputList((prevState) => {
        const newInputs = {
            startDate: undefined,
            completionDate: undefined,
            disabled: false,
            checked: false,
        };
        return [...prevState, newInputs];
        });
    };

    const handleRemoveClick = (index) => {
        const list = [...inputList];
        list.splice(index, 1);
        setInputList(list);
    };

    return (
        <div>
            <div>App</div>
            {inputList.map((input, i) => {
                return (
                <div key={i}>
                    <br />
                    <div>
                    <label>
                        Start Date:
                        <input
                        name="startDate"
                        type="text"
                        onChange={(e) => handleInputChange(e, i)}
                        placeholder="Start Date"
                        />
                    </label>
                    </div>
                    <div>
                    <label>
                        Completion Date:
                        <input
                        name="completionDate"
                        type="text"
                        disabled={input.disabled}
                        onChange={(e) => handleInputChange(e, i)}
                        placeholder="Completion Date"
                        />
                    </label>
                    </div>
                    <div>
                    <label htmlFor={`checkbox-${i}`} style={{ cursor: "pointer" }}>
                        <input
                        id={`checkbox-${i}`}
                        name="inline"
                        type="checkbox"
                        checked={input.checked}
                        onChange={(e) => handleInputChange(e, i)}
                        />
                        {`Checkbox-${i}`}
                    </label>
                    </div>
                    <br />
                    {inputList.length - 1 === i && (
                    <button onClick={() => handleAddClick()}>+ New Section</button>
                    )}
                    {inputList.length !== 1 && (
                        <button onClick={() => handleRemoveClick(i)}>
                            - Remove Section
                        </button>
                    )}
                </div>
                );
            })}
        </div>
    );
}

ReactDOM.render(<App />, document.querySelector('.react'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div class='react'></div>

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文