javascript 无法在提交时获取选中复选框的列表

2nc8po8w  于 2023-04-28  发布在  Java
关注(0)|答案(1)|浏览(214)

我有一个NextJS应用程序,其中有这样的表单:

<form id='roles-form' action='#' onSubmit={handleSubmit}>
  <ul className='h-56 overflow-y-auto p-3'>
    {roles.role.map((role) => {
      return (
        <li key={role.roleId}>
          <div className='flex rounded p-3 hover:bg-gray-100'>
            <label className='relative inline-flex w-full cursor-pointer items-center'>
              <input
                type='checkbox'
                name='roles'
                value={role.roleId}
                onChange={(event) => {
                  toast.info(event.target.value);
                }}
                className='peer sr-only'
              />
              <div className="peer h-5 w-9 rounded-full bg-gray-200 after:absolute after:left-[2px] after:top-[2px] after:h-4 after:w-4 after:rounded-full after:border after:border-gray-300 after:bg-white after:transition-all after:content-[''] peer-checked:bg-primary-600 peer-checked:after:translate-x-full peer-checked:after:border-white peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-primary-300"></div>
              <span className='ml-3 text-sm font-medium text-gray-900'>{role.name}</span>
            </label>
          </div>
        </li>
      );
    })}
  </ul>
  <button
    type='submit'
    className='block w-full rounded-b-lg bg-gray-50 py-3 text-center text-sm font-medium text-gray-900 hover:bg-gray-100'>
    <div className='inline-flex items-center '>Assign</div>
  </button>
</form>

基本上,它只是一个表单,带有一堆复选框,用于指定给用户的角色。
提交表单后,我不知道如何获取值并获得选中的复选框。我没有尝试在useState中这样做,因为角色列表是动态的,这听起来很复杂,所以我没有跟踪复选框的状态,只是尝试在提交时捕获它们。

const handleSubmit = (event: FormEvent<HTMLFormElement>) => {
  event.preventDefault();

  const form = document.getElementById('roles-form') as HTMLFormElement;
  const formData = new FormData(form);

  console.log(event.target);
  console.log(formData);
};
avwztpqn

avwztpqn1#

使用复选框上的更改事件来更新组件的状态,并在handleSubmit中访问它:

const [checkedState, setCheckedState] = useState({});
...
onChange={(event) => {
  setCheckedState((state) => ({ ...state, [role.roleId]: event.target.checked
  ...
}}
...
const handleSubmit = (event) => {
  console.log(checkedState);
}

相关问题