Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

141
Vistas
Prevent keys that are not the enter key from triggering submit function

I am using a react components system(mantine). I have a select field and I want to select an option with any key and submit using the enter key only.

The problem right now is that once the dropdown appears and I press any key it calls the function and sends the empty string i set. The onSubmit won't work without a submit button present in the form, setting display as none still didn't get it to submit. So, I resulted to this.

import React, { useState, useRef } from "react";
import { useNavigate } from "react-router-dom";
import { Text, Select } from "@mantine/core";
import { Icon } from "@iconify/react";
import axios from "axios";
import { api } from "../helpers/api";

const Home = () => {
  const [joblist, setJoblist] = React.useState("");
  const [error, setError] = useState(null);
  const [loading, setLoading] = useState(false);
  const history = useNavigate();
  const selectForm = useRef(null);
  function handleSubmit(e) {
    if (e.key === "Enter" && e.preventDefault()) {
      selectForm.current.submit();
    }

    setJoblist("");
    console.log(joblist);
    setLoading(true);
    const uu = {
      jobs: joblist,
    };
    console.log(uu);
    console.log(api.jobs);
    fetch(api.jobs, {
      method: "POST",
      headers: {
        "Access-Control-Allow-Origin": "http://127.0.0.1:8000/",
        "Content-Type": "application/json",
      },
      body: JSON.stringify(uu),
    })
      .then((res) => {
        console.log(res.data);
        setLoading(false);
      })
      .catch((err) => {
        console.log(err);
        setLoading(false);
        setError(err.message || err);
      });
  }

  return (
    <div>
    
      <form ref={selectForm} onKeyDown={handleSubmit}>
        <Select
          label="Your favorite framework/library"
          placeholder="Pick one"
          searchable
          clearable
          nothingFound="No options"
          value={joblist}
          onChange={setJoblist}
          data={[
            { value: "react", label: "React" },
            { value: "ng", label: "Angular" },
            { value: "svelte", label: "Svelte" },
            { value: "vue", label: "Vue" },
          ]}
          style={{
            width: "608px",
            marginLeft: "294px",
            marginTop: "-100px",
          }}
        />
      </form>
    </div>
  );
};

export default Home;
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

With

if (e.key === "Enter" && e.preventDefault()) {
  selectForm.current.submit();
}

When e.key === "Enter" is false, the condition evaluation stops right there. So try:

e.preventDefault()
if (e.key === "Enter") {
  selectForm.current.submit();
}

And you may need this to prevent executing the rest of the code (but that is unclear...)

else {
  return
}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda