如何获得反应中形式的值

发布于 2025-02-09 15:35:58 字数 4424 浏览 0 评论 0原文

我试图以React中形式获取所有输入元素的值。 这是我



export default function MarkAttendance() {

  const dispatch = useDispatch();
  const navigate = useNavigate();

  const { users, loading, error } = useSelector((state) => state.userList);
  const today = new Date().toISOString().substr(0, 10);
  const { userInfo } = useSelector((state) => state.userLogin);
  const [firstTime, setFirstTime] = useState('')
  const [secondTime, setSecondTime] = useState('')
  const [attenandance, setAttendance] = useState({ id: null, date: today, first_time: "Present", second_time: "Present" });

  useEffect(() => {
    if (userInfo && userInfo.isAdmin) {
      dispatch(listUsers());

    } else {
      navigate("/login");
    }

  }, [dispatch, userInfo, navigate]);

  const handleSubmit = (e) => {
    e.preventDefault();


    for (let i = 0; i < users.length; i++) {
      setAttendance({ id: users[i].id, date: today, first_time: firstTime, second_time: secondTime });

      postAttendance(attenandance);

    }
  }

  return (
      <section>
        <div className="row">
          <div className="col-md-12 text-dark">
            <h3>Mark Attendance</h3> for <h4>{today}</h4>'s meal
          </div>
        </div>
        {loading ? (
          <Loader />
        ) : error ? (
          <Message variant="danger">{error}</Message>
        ) : (
          <form onSubmit={handleSubmit}>
            <table className="table table-bordered">
              <thead>
                <tr>
                  <th scope="col">#</th>
                  <th scope="col">Name</th>
                  <th scope="col">Room no.</th>
                  <th scope="col">First Time</th>
                  <th scope="col">Second Time</th>
                </tr>
              </thead>
              <tbody>

                {users.map((user) => (
                  <tr key={user.id}>


                    <th scope="row" name="userId">{user.id}</th>
                    <td className="form-group">
                      <input

                        type="text"
                        className="form-control"
                        id="table-name"
                        name="username"
                        value={user.username}

                      />
                    </td>
                    <td className="form-group">
                      <input
                        type="text"
                        className="form-control"
                        id="table-room"
                        name="room"
                        value={user.room}

                      />

                    </td>

                    <td>
                      <select name={`firstAttendance${user.id}`} onChange={(e) => (e.target.value)} className="form-control" id="table-first-time">
                        <option value="present">Present ✓</option>
                        <option value="absent">Absent X</option>
                        <option value="double">Double 2</option>
                      </select>

                    </td>
                    <td>
                      <select name={`secondAttendance${user.id}`} onChange={(e) => (e.target.value)} className="form-control" id="table-second-time">
                        <option value="present">Present ✓</option>
                        <option value="absent">Absent X</option>
                        <option value="double">Double 2</option>
                      </select>

                    </td>
                  </tr>
                ))}
              </tbody>
            </table>

            <button type="submit" className="btn btn-primary">
              Submit
            </button>
          </form>

        )}
      </section >
  );
}

想要的表单是获取选择值以及用户ID并将其发送回服务器。我不知道如何获取用户ID以及他在表格中选择了什么。它是由地图功能制成的,这意味着名称属性都是相同的。

我尝试的

  1. 是尝试动态地更改name属性,但它仍然给我不确定。
  2. 我尝试使用usestate挂钩,但它只给了我最后一个用户的价值,这也改变了其他用户的价值,因为所有挂钩只有一个挂钩。

因此,如何在ReactJ中以形式获取所有值。谢谢

I am trying to get the values of all the input elements in a form in React.
Here is my form



export default function MarkAttendance() {

  const dispatch = useDispatch();
  const navigate = useNavigate();

  const { users, loading, error } = useSelector((state) => state.userList);
  const today = new Date().toISOString().substr(0, 10);
  const { userInfo } = useSelector((state) => state.userLogin);
  const [firstTime, setFirstTime] = useState('')
  const [secondTime, setSecondTime] = useState('')
  const [attenandance, setAttendance] = useState({ id: null, date: today, first_time: "Present", second_time: "Present" });

  useEffect(() => {
    if (userInfo && userInfo.isAdmin) {
      dispatch(listUsers());

    } else {
      navigate("/login");
    }

  }, [dispatch, userInfo, navigate]);

  const handleSubmit = (e) => {
    e.preventDefault();


    for (let i = 0; i < users.length; i++) {
      setAttendance({ id: users[i].id, date: today, first_time: firstTime, second_time: secondTime });

      postAttendance(attenandance);

    }
  }

  return (
      <section>
        <div className="row">
          <div className="col-md-12 text-dark">
            <h3>Mark Attendance</h3> for <h4>{today}</h4>'s meal
          </div>
        </div>
        {loading ? (
          <Loader />
        ) : error ? (
          <Message variant="danger">{error}</Message>
        ) : (
          <form onSubmit={handleSubmit}>
            <table className="table table-bordered">
              <thead>
                <tr>
                  <th scope="col">#</th>
                  <th scope="col">Name</th>
                  <th scope="col">Room no.</th>
                  <th scope="col">First Time</th>
                  <th scope="col">Second Time</th>
                </tr>
              </thead>
              <tbody>

                {users.map((user) => (
                  <tr key={user.id}>


                    <th scope="row" name="userId">{user.id}</th>
                    <td className="form-group">
                      <input

                        type="text"
                        className="form-control"
                        id="table-name"
                        name="username"
                        value={user.username}

                      />
                    </td>
                    <td className="form-group">
                      <input
                        type="text"
                        className="form-control"
                        id="table-room"
                        name="room"
                        value={user.room}

                      />

                    </td>

                    <td>
                      <select name={`firstAttendance${user.id}`} onChange={(e) => (e.target.value)} className="form-control" id="table-first-time">
                        <option value="present">Present ✓</option>
                        <option value="absent">Absent X</option>
                        <option value="double">Double 2</option>
                      </select>

                    </td>
                    <td>
                      <select name={`secondAttendance${user.id}`} onChange={(e) => (e.target.value)} className="form-control" id="table-second-time">
                        <option value="present">Present ✓</option>
                        <option value="absent">Absent X</option>
                        <option value="double">Double 2</option>
                      </select>

                    </td>
                  </tr>
                ))}
              </tbody>
            </table>

            <button type="submit" className="btn btn-primary">
              Submit
            </button>
          </form>

        )}
      </section >
  );
}

What I am want is get the select values along with user ids and send it back to the server . I don't know how to get the user id and what he has selected in the form . It is made by a map function which means name attriutes are all gonna be same .

What I have tried

  1. I tried to change the name attribute dynamically but it still give me undefined.
  2. I tried to use useState hook but it only gives me the value of last users and this also changes the value of other users since there is only one hook for all.

So how to get all the values in a form in reactjs. Thanks

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

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

发布评论

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

评论(1

蓝眸 2025-02-16 15:35:58

因此,一段时间后,我终于使用了技巧来获取所有值。我所做的是通过将每个用户的用户-ID 单独的标签提供给每个id标签。 >标签ID。每个用户都有一个唯一的ID,因此输入和选择标签也是如此。然后提取所需输入的值first_timesecond_time通过提供user-id,遍历每个输入,并为所有用户和所有用户获取单独的值通过postAttendance派遣它们。
它的外观是:


  const handleSubmit = (e) => {
    e.preventDefault();
    try {
      const attendanceExtractor = (e, id) => {
        let first_time = e.target.elements[`first-attendance-${id}`].value;
        let second_time = e.target.elements[`second-attendance-${id}`].value;

        return [first_time, second_time]
      }  // writing a separate function for extracting each value


// then looping through each 
      for (let index = 0; index < userIds.length; index++) {
        let id = userIds[index];

        const attendance = {
          student: id,
          date: date,
          first_time: attendanceExtractor(e, id)[0],
          second_time: attendanceExtractor(e, id)[1]
        }
        dispatch(postAttendance(attendance, id))
      }
      alert("All the attendance is submitted successfully")
      dispatch(getAttendance());
      let count = counter(getAttendanceObj, date);
      setTotal(count)

      console.log(count)
    } catch (error) {

    }
  }

形式看起来像这样:

  <form className="form" onSubmit={handleSubmit}>

              <table className="table table-bordered">
                <thead>
                  <tr>
                    <th scope="col">#</th>
                    <th scope="col">Name</th>
                    <th scope="col">Room no.</th>
                    <th scope="col">First Time</th>
                    <th scope="col">Second Time</th>
                    <th scope="col">Status</th>
                  </tr>
                </thead>

                {users.map((user) => (


                  <tbody>




                    <tr key={user.id}>


                      <th scope="row" id={`user-id-${user.id}}`}>{user.id}</th>
                      <td className="form-group">
                        <input

                          type="text"
                          className="form-control"
                          id={`table-name-${user.id}`}
                          name="username"
                          value={user.username}

                        />
                      </td>
                      <td className="form-group">
                        <input
                          type="text"
                          className="form-control"
                          id={`table-ropm-${user.id}`}
                          name="room"
                          value={user.room}

                        />

                      </td>

                      <td>
                        <select id={`first-attendance-${user.id}`} onChange={(e) => (e.target.value)} className="form-control" >
                          <option value="present">Present ✓</option>
                          <option value="absent">Absent X</option>
                          <option value="double">Double 2</option>
                        </select>

                      </td>
                      <td>
                        <select id={`second-attendance-${user.id}`} onChange={(e) => (e.target.value)} className="form-control" > // FOCUS ON ID
                          <option value="present">Present ✓</option>
                          <option value="absent">Absent X</option>
                          <option value="double">Double 2</option>
                        </select>

                      </td>
                      <td>
                        <i class="bi bi-check" ></i>
                      </td>
                    </tr>

                  </tbody>
                ))
                }

              </table>
              <button type="submit" className="btn btn-primary">
                Submit
              </button>

            </form>

So after some time , I finally use the trick to get all the values. What I did is give each input tag , a separate id by incorporating the user-id of each user in input tag id .As each user have a unique id so did the input and selection tag . Then extracting the values of desired input first_time and second_time by providing user-id , looping through each inputs and getting separate values for all the users and dispatching them on postAttendance.
Here is how it look like:


  const handleSubmit = (e) => {
    e.preventDefault();
    try {
      const attendanceExtractor = (e, id) => {
        let first_time = e.target.elements[`first-attendance-${id}`].value;
        let second_time = e.target.elements[`second-attendance-${id}`].value;

        return [first_time, second_time]
      }  // writing a separate function for extracting each value


// then looping through each 
      for (let index = 0; index < userIds.length; index++) {
        let id = userIds[index];

        const attendance = {
          student: id,
          date: date,
          first_time: attendanceExtractor(e, id)[0],
          second_time: attendanceExtractor(e, id)[1]
        }
        dispatch(postAttendance(attendance, id))
      }
      alert("All the attendance is submitted successfully")
      dispatch(getAttendance());
      let count = counter(getAttendanceObj, date);
      setTotal(count)

      console.log(count)
    } catch (error) {

    }
  }

and the form look like this:

  <form className="form" onSubmit={handleSubmit}>

              <table className="table table-bordered">
                <thead>
                  <tr>
                    <th scope="col">#</th>
                    <th scope="col">Name</th>
                    <th scope="col">Room no.</th>
                    <th scope="col">First Time</th>
                    <th scope="col">Second Time</th>
                    <th scope="col">Status</th>
                  </tr>
                </thead>

                {users.map((user) => (


                  <tbody>




                    <tr key={user.id}>


                      <th scope="row" id={`user-id-${user.id}}`}>{user.id}</th>
                      <td className="form-group">
                        <input

                          type="text"
                          className="form-control"
                          id={`table-name-${user.id}`}
                          name="username"
                          value={user.username}

                        />
                      </td>
                      <td className="form-group">
                        <input
                          type="text"
                          className="form-control"
                          id={`table-ropm-${user.id}`}
                          name="room"
                          value={user.room}

                        />

                      </td>

                      <td>
                        <select id={`first-attendance-${user.id}`} onChange={(e) => (e.target.value)} className="form-control" >
                          <option value="present">Present ✓</option>
                          <option value="absent">Absent X</option>
                          <option value="double">Double 2</option>
                        </select>

                      </td>
                      <td>
                        <select id={`second-attendance-${user.id}`} onChange={(e) => (e.target.value)} className="form-control" > // FOCUS ON ID
                          <option value="present">Present ✓</option>
                          <option value="absent">Absent X</option>
                          <option value="double">Double 2</option>
                        </select>

                      </td>
                      <td>
                        <i class="bi bi-check" ></i>
                      </td>
                    </tr>

                  </tbody>
                ))
                }

              </table>
              <button type="submit" className="btn btn-primary">
                Submit
              </button>

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