I am having a hard time retrieving the value of a selected element, in a dropdown list.
I tried debugging it, but could not get the value.
Tried to console log e.target.value
, but it didn’t work.
Any idea what might be wrong in my code?
const [values, setValues] = useState({
lastName: "",
firstName: "",
lastNameHiragana: "",
firstNameHiragana: "",
birthday: "",
sex: "",
telephone: "",
email: "",
enterDate: "",
});
// inputs to be created in form
const inputs = [
{
id: 1,
name: "lastName",
type: "text",
label: "姓",
required: true,
},
{other objects in between},
{
id: 6,
name: "sex",
type: "select",
required: true,
values: ["男性", "女性"],
label: "性別",
},
]
const onChange = (e) => {
setValues({ ...values, [e.target.name]: e.target.value });
};
// Form makes input fields, according to the input type(defined above)
<form>
{inputs
.filter((input) => input.id <= 8)
.map((input) => (
<div key={input.id} className="mb-3">
<label htmlFor={input.name} className="form-label m-0">
{input.label}
</label>
{input.type === "select" ? (
<select
name={input.name}
id={input.id}
className="form-select"
onChange={onChange}
>
{input.values.map((value) => {
<option value={optionValue} key={value}>
{value}
</option>
})}
</select>
) : (
<input
ref={inputs.id}
name={input.name}
type={input.type}
className={`form-control ${styles.input} `}
id={input.id}
required={input.required}
onChange={onChange}
/>
)}
<span className={`text-danger text-center`}>
{errorMessage[input.name]}
</span>
</div>
)
)}
</form>
2
Answers
In this code,
optionValue
is not definedChange it to
value
and you should get the correct output.You can use the react state to store and get the select box value as below