Home > Back-end >  calling method onChange in select attribute
calling method onChange in select attribute

Time:03-07

I have to call a method when user changes dropdown list ,handleChange() method should be called.

and it should print both the values. we have 2 attribute country as well as activerequests

import React from 'react'
import { useFormik } from 'formik';
import * as Yup from 'yup';

function YourActionNew() {

    const initialValues={
        country: '',
        activerequests:''
    }

    const onSubmit=(values:any)=>{
        console.log('Form Data',values);
    }

    const handleChange = async ( event: any) => {
        alert("Visited field " JSON.stringify(event.target.values));  
      
    };


     const validationSchema = Yup.object({
        country:Yup.string().required('Required'),
        activerequests:Yup.string().required('Required')
     })

    const formik = useFormik({
        initialValues,
        onSubmit,
        validationSchema
    });

         console.log("Visited field " JSON.stringify(formik.values));

    return (
      <div>
        <form >
        
            <div className='form-control'>
            <label htmlFor='country'>Country</label>
            <input type='text' id='country'  name='country' onChange={formik.handleChange} onBlur={formik.handleBlur} value={formik.values.country}/>
            {formik.touched.country  && formik.errors.country? <div className='error'>{formik.errors.country}</div>:null}
            </div>

            <div className="form-control">
            <label htmlFor="activerequests">Active Requests</label>
            <select name="activerequests"  onChange= {formik.handleChange}  onBlur={formik.handleBlur}  value={formik.values.activerequests}>
                <option value="All"  onChange={formik.handleChange}>All </option>  
                <option value="YES" onChange={formik.handleChange}>Yes </option>
                <option value="NO" onChange={formik.handleChange}>No</option>          
             </select>
            </div>

            <button type="submit">Submit</button>
        </form>
     </div>
  )
}

export default  YourActionNew

enter image description here

when in select tag I write onChange= {(e)=>{handleChange(e)}} instead of onChange={formik.handleChange} then method get called but it prints undefined.

what my requirement is when user changed values in dropdown list it shoud print both the values. I have to pass both the values in API.

CodePudding user response:

I think there is one mistake while printing value in handleChange function

it should be

alert("Visited field " JSON.stringify(event.target.value));

remove s from the value

CodePudding user response:

I suppose you want to make an API call when the user submits the form. To do that, you should bind the onSubmit function that you have defined to the form:

<form onSubmit={formik.handleSubmit}>
  • Related