Alexandra
Alexandra

Reputation: 181

How capture the key from a select?

I have an html select element that I am filling from a database (List of companies) Data

I am trying to capture the 2 values ​​in the select

The field "company name (alias)" and The CompanyID field

I can't use an index in the map since this list is ordered in a specific way and the id(pk) needs to match the name field

But I can't capture the 2 data

Index

function ManejadorDeCambios(e) {
  setformDato((estadoAnterior) => ({
    ...estadoAnterior,
    [e.target.name]: {
      pk: e.target.key,
      titulo: e.target.value,
    },
  }));
}

<Console stateName={formDato} />
<label htmlFor="Compania">Compañia:</label>
<Select
  name="Dato"
  id="Dato"
  on_change={ManejadorDeCambios}
  db={datos}
/>

select Component

const Select = function ({ name, db, on_change }) {
  return (
    <>
      {Array.isArray(db) ? (
        <select name={name} onChange={on_change}>
          <option key="0" value="-- Seleccionar --">
            -- Seleccionar --
          </option>
          {db.map((x, index) => (
            <option key={x.companiaID} value={x.alias}>
              {x.alias}
            </option>
          ))}
        </select>
      ) : null}
    </>
  );
};
export default Select;

How can I capture the value of key?

Upvotes: 0

Views: 33

Answers (1)

Abito Prakash
Abito Prakash

Reputation: 4770

One approach would be to change the arguments of ManejadorDeCambios

function ManejadorDeCambios(event, name) {
  setformDato((estadoAnterior) => ({
    ...estadoAnterior,
    [name]: {
      pk: event.target.key,
      titulo: event.target.value
    },
  }));
}

And change the onChange handler for select accordingly

<select name={name} onChange={(event) => on_change(event, name)}>

Upvotes: 1

Related Questions