mardi 17 mai 2022

how to get the values of a checked checkbox and the output it on a input field

I am trying to get the checked values of a checkbox and then display them in a field. I have two files the index which has the input field and then the checkbox is made in a modal which is a different component, the selectlanguage. I want that when a user checks one or more checkbox(es), the value(s) appears on the input and when unchecked, the value leaves the field.

Presently, what I am able to achieve is only a single value appearing on the input field.

Here is a snippet of the code.

index.js

import React, { useState } from "react";
import SelectLanguage from "../../components/modal/selectLanguage";

const index = () => {
const [chosenLanguage, setChosenLanguage] = useState([]);

function checkLanguage(e) {
  setChosenLanguage(e.target.name);
};

<label className="relative block p-3 border-b-2 border-gray-200 w-full" for="languages">
  <span for="languages">languages</span>
  <input
    id="languages"
    type="text"
    placeholder="Spanish, Arabic"
    autoComplete="off"
    onClick={languageShowModal}
    value={chosenLanguage}
  />
</label>
}

export default index;

selectlanguage.js

import { useState } from "react";

export default function SelectLanguage({ open, handleClose, checkLanguage }) {
  const handleCheckbox = (e) => {
    alert(e.target.name);
  };

  return open ? (
    <div>
      <label>
        <input type="checkbox" name="spanish" onChange={checkLanguage} />
        <span>spanish</span>
      </label>
      <label>
        <input type="checkbox" name="spanish" onChange={checkLanguage} />
        <span>french</span>
      </label>
      <label>
        <input type="checkbox" name="spanish" onChange={checkLanguage} />
        <span>arabic</span>
      </label>
    </div>
  ) : (
    ""
  );
}




Aucun commentaire:

Enregistrer un commentaire