I have a country dropdown. When the user select any country, its id sent to the database instead of country name. How can I get the id of a selected option?
function RegisterPlayer() {
const handleSubmit = (values, { setFieldError }) => {
const RegisterAsPlayerForm = {
full_name: values.fullname,
display_name: values.displayname,
nick_name: values.nickname,
dob: values.dob,
gender: values.gender,
country: values.country,
birth_city: values.city,
address: values.address,
phone: values.phone,
sport_id: values.sport,
speciality_id: values.speciality,
user_id: values.user_id,
file: values.profilephoto,
coverPhoto: values.coverPhoto,
};
let access_token = "fj7VfkpK8Yo4gZwGf4crRPIA5vHj1xw_";
axios
.post(
`http://192.168.18.8/goc-backend/api/web/index.php/v1/player/registerplayer`,
{ RegisterAsPlayerForm },
{
headers: {
Authorization: `Bearer ${access_token}`,
Here is select option code:
<select
className="inputBox"
type="option" name="country" onChange={handleChange}
onBlur={handleBlur} value={values.country} id="country" >
<option value=""> Country </option>
{countriesname.map((getcountry) => (
<option>{getcountry.name} </option> ))}
</select>
<p className="req-errors">
{touched.country && errors.country} </p>
CodePudding user response:
Give you options values. Presumably:
<option value={getcountry.id}>{getcountry.name}</option>
Or however getcountry
stores the value you're looking for. HTML <option>
elements have a value
attribute to store their respective values.
CodePudding user response:
add your option as so
<select
onChange={handleChangeCountry}
value={countrySelected} >
{countriesname.map((getcountry) => (
<option value=getcountry.id>{getcountry.name}</option>
))}
</select>
and in your handleChangeCountry
const handleChangeCountry = (e) => {
setCountrySelected( e.target.value );
};
CodePudding user response:
When you render the options give the required id to the value field of that option
<option value={getcountry.id}>{getcountry.name} </option>
and in your onChange function of the select component, you can get the value using,
e.target.value