K Y
K Y

Reputation: 211

Get Selected Values from React-bootstrap Forms without Submit Button

I have a form that looks like this (the same as the React Bootstrap doc)

 <Form.Group controlId="exampleForm.ControlSelect2">
    <Form.Label>Example multiple select</Form.Label>
    <Form.Control as="select" multiple>
      <option>1</option>
      <option>2</option>
      <option>3</option>
      <option>4</option>
      <option>5</option>
    </Form.Control>
  </Form.Group>

I would like to obtain the value selected. For example if I click and dragged from 1 to 3, I will have perhaps an object recording those selections are active, without using a submit button.

enter image description here

I tried search online but couldn't find much on how to do this. This one got closest to what I needed, but onChange only record entries that has been clicked, not selected.

Upvotes: 1

Views: 320

Answers (1)

Namrata Sanja
Namrata Sanja

Reputation: 236

  const [values, setValues] = useState([]);

  function handleChange(e) {
    console.log(Array.from(e.currentTarget.selectedOptions, (v) => v.value));
    setValues(Array.from(e.currentTarget.selectedOptions, (v) => v.value));    
  }

     <Form>
      <Form.Group controlId="exampleForm.ControlSelect2">
        <Form.Label>Example multiple select</Form.Label>
        <Form.Control as="select" multiple value={values} onChange={handleChange} >
          <option>1</option>
          <option>2</option>
          <option>3</option>
          <option>4</option>
          <option>5</option>
        </Form.Control>
      </Form.Group>
    </Form>

Create this function on select of dropdown options and store all selected value in values array of state.

Upvotes: 2

Related Questions