I have a form that has a select-multiple field. It is just getting one value that is first clicked but not the other values that are clicked after clicking the first one. Hhow to get the values? Below is my code.
assignment of state, Here shift and board are the state to store the values of multi-select field
const [formData, setFormData] = useState({
name: "",
photo: "",
adhar: "",
phone: "",
location: "",
fullAddress: "",
age: "",
gender: 0,
schooName: "",
experience: "",
teachForNoDays: "",
shift: [],
subject: "",
teachClass: "",
board: [],
homeTuition: false,
fees: "",
homeTuitionFees: "",
});
onChange function
const changeFormData = (e) => {
// this is how we do when to specifically define a type in the target
const { name, type } = e.target;
console.log(e.target.value);
setFormData({
...formData,
[name]: e.target[type === "checkbox" ? "checked" : "value"],
});
};
the fields, only putting up the shift one here
<select
name="shift"
id="shift"
defaultValue={shift}
size={2}
onChange={(e) => changeFormData(e)}
multiple={true}
>
<option value="Evening">Evening</option>
<option value="Morning">Morning</option>
</select>
<select> has an e.target.options field which is an array containing all the selected options.
You should take that into consideration in changeFormData().
Don't forget to properly "control" the value of your select component by assigning it with the current value:
<select
...
value={formData.shift}
multiple
>
...
</select>