选项在输入数值后重置

huangapple go评论84阅读模式
英文:

option resetting after typing a value

问题

当用户选择"other"选项时,会出现一个输入框,用户可以在其中输入自己的文本并将其存储在全局上下文的变量中。

问题出在当用户输入一个值后,它会更改为选项列表中的第一个选项。

如果开始在"other"输入框中输入文本,选项会重置为第一个选项。您希望它保持在"other"选项。

英文:

Basically, when the user chooses the "other" option an input appears and he will be able to type his own text and store it inside a variable in the global context.

The problem is when the user types a value it changes to the first option in my list of options.

import { useEffect, useState } from "react";
import { useAppContext } from "../context/appContext";

const FormRowSelect = ({
  labelText,
  name,
  value,
  handleChange,
  list,
  optionsIsActivated,
}) => {
  const [inputValue, setInputValue] = useState(""); // new state variable
  var newList = [...list, "other"];

  const { handleChange2 } = useAppContext(); // because i already used handleChange i made another function 

  const handleInputChange = (e) => {
    setInputValue(e.target.value);
    console.log(inputValue);
    console.log(inputValue);
    console.log(e.target.value);
    handleChange2({ name, value: inputValue });
  };
  return (
    <div className="formRow">
      <label htmlFor={name} className="form-label">
        {labelText || name}
      </label>

      <select
        name={name}
        value={value}
        onChange={handleChange}
        className="form-select choosebtn"
        style={{ color: "black" }}
      >
        {newList.map((itemValue, index) => {
          return (
            <option key={index} value={itemValue}>
              {itemValue}
            </option>
          );
        })}
      </select>

      {optionsIsActivated && !list.includes(value) && (
        <>
          <input
            type="text"
            value={inputValue}
            name={name}
            onChange={handleInputChange}
            className="form-input other-input"
          />
        </>
      )}
    </div>
  );
};

export default FormRowSelect;

handleChange function

const handleChange2 = ({ name, value }) => {
dispatch({ type: "HANDLE_CHANGE", payload: { name, value } });
};

Here is how I used my component (in case you need it):

import { useAppContext } from "../../context/appContext";
import Wrapper from "../../assets/wrappers/DashboardFormPage";
import {
  FormRow,
  Alert,
  FormRowSelect,
  CheckBoxOptions,
} from "../../components";
import CheckBox from "../../components/checkBox";
import { useEffect, useState } from "react";

const AllCustomer = () => {
  const {
    isLoading,
    isEditing,
    showAlert,
    handleChange,
    clearValues,
   
    companypercentage,
    companypercentageOptions,
  
  } = useAppContext();

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

  const handleJobInput = (e) => {
    const name = e.target.name;
    const value = e.target.value;
    // console.log(`${name} : ${value}`);

    handleChange({ name, value });
  };

  return (
    <Wrapper>
      <form className="form">
        <h3>{isEditing ? "edit job" : "add job"}</h3>
        {showAlert && <Alert />}
        <div className="form-center">
          
          <FormRowSelect
            name="companypercentage"
            value={companypercentage}
            handleChange={handleJobInput}
            list={companypercentageOptions}
            optionsIsActivated={true}
            labelText="companyPercentage:"
          />
          
          
          <div className="btn-container">
            <button
              type="submit"
              className="btn btn-block submit-btn"
              onClick={handleSubmit}
              disabled={isLoading}
            >
              submit
            </button>
            <button
              className="btn btn-block submit-btn"
              onClick={(e) => {
                e.preventDefault();
                clearValues();
              }}
            >
              clear
            </button>
          </div>
        </div>
      </form>
    </Wrapper>
  );
};

export default AllCustomer;

Here is my appContext.js

const initialState = {
companypercentage: "قيد الانتظار", // I'm trying this 
companypercentageOptions: ["قيد الانتظار"],
excesscashcustomer: "قيد الانتظار",
excesscashcustomerOptions: ["قيد الانتظار"],
};
const handleChange = ({ name, value }) => {
dispatch({ type: "HANDLE_CHANGE", payload: { name, value } });
};
const handleChange2 = ({ name, value }) => { //i duplicated as a temporarily solution for myhandleChange event
dispatch({ type: "HANDLE_CHANGE", payload: { name, value } });
};
return (
<AppContext.Provider
value={{
...state,
handleChange1,
handleChange2,
}}
>
{children}
</AppContext.Provider>
);
};
const useAppContext = () => {
return useContext(AppContext);
};
export { AppProvider, initialState, useAppContext };

reducer.js

if (action.type === HANDLE_CHANGE) {
return {
...state,
[action.payload.name]: action.payload.value,
page: 1,
};
}

when start typing in the "other" input value options are resetting to the first index. I want it to stay on "other"

答案1

得分: 1

我相信如果您只删除中设置一个"defaultValue",但也不是必需的。

希望对您有所帮助!

英文:

I believe that if you only remove the "value" option from the <select> tag, your issue will be solved.
The value shown in the select will be handled by your options.

You can have a "defaultValue" in your <select> if you wish, but also not needed.

Hope it helps!

huangapple
  • 本文由 发表于 2023年4月11日 15:50:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/75983579.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定