简体   繁体   中英

Javascript Remove Focus on Enter Key Press

How can I remove the focus of either input box when I press the "enter" key?

I have this code:

import React, { useState } from "react";

import "antd/dist/antd.css";
import { Form, Input, Button, Card } from "antd";

function Login() {
  const [loadings, setloadings] = useState(false);
  const [disabledLoading, setDisabledLoading] = useState(false);

  function changeloading() {
    setloadings(true);
    setDisabledLoading(true);
    setTimeout(() => {
      setloadings(false);
    }, 1630);
  }

  function passwordEnterPress(e) {
    e.target.blur();
  }

  return (
    <div>
      <Card className="home-card">
        <Form>
          <Form.Item name="Username">
            <Input name="username" onPressEnter={passwordEnterPress} />
          </Form.Item>
          <Form.Item name="Password">
            <Input.Password name="password" onPressEnter={passwordEnterPress} />
          </Form.Item>
          <Form.Item>
            <Button
              type="primary"
              htmlType="submit"
              onClick={() => changeloading()}
            >
              Log in
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
}

export default Login;

Codesandbox

EDIT per the documentation link , there's a blur function that I could call to remove the focus, but I don't know how to trigger the function on submit and target the input fields.

If I select either input, it will be focused; however, when I pressed "enter" to submit the form, the focus won't go away. I want the focus to disappear whenever I press the "enter" key that submits the form.

It's worth mentioning that I don't want to forcibly overwrite the focus border. I only want the border to disappear whenever I click the login button (which is already working) or press the "enter" key (entire point of this question).

Thanks in advance.

In order to call the blur function you would need to get instance of the input tag which you can do by using ref or simply you can call the onPressEnter attribute given by and

            <Input.Password name="password" onPressEnter={passwordEnterPress} />

then you can write the required functionality like bluring out

   function passwordEnterPress(e) {
     e.target.blur()
   }

sorry for my poor editing skills below is the code which you can run in your code sandbox. Please note you have to the mouse out of the input box

import React, { useState } from "react";
import "antd/dist/antd.css";
import { Form, Input, Button, Card } from "antd";

function Login() {
  const [loadings, setloadings] = useState(false);
  const [disabledLoading, setDisabledLoading] = useState(false);
  function changeloading() {
    setloadings(true);
    setDisabledLoading(true);
    setTimeout(() => {
      setloadings(false);
    }, 1630);
  }

  function passwordEnterPress(e) {
    e.target.blur()
  }
  return (
    <div>
      <Card className="home-card">
        <Form>
          <Form.Item name="Username">
            <Input name="username" />
          </Form.Item>
          <Form.Item name="Password">
            <Input.Password name="password" onPressEnter={passwordEnterPress} />
          </Form.Item>
          <Form.Item>
            <Button
              type="primary"
              htmlType="submit"
              onClick={() => changeloading()}
            >
              Log in
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
}

export default Login;

inorder to lose focuse from input when enter key is pressed, you should handle key up event of input,as shown below

function handleKeyUp(event) {
 //key code for enter
 if (event.keyCode === 13) {
   event.preventDefault();
   event.target.blur();
 }
}

now assign this function to on key up event of input box like this

<Input name="username" onKeyUp={handleKeyUp} />

now to clear focus of input on form submit, you can create refernce to both input as shown below

let userNameRef = React.createRef();
let passwordRef = React.createRef();

assign this to input as below

<Input ref={userNameRef} name="username" onKeyUp={handleKeyUp} />
 <Input.Password ref={passwordRef} name="password" />

use these reference to clear focus whenever you want as

userNameRef.current.blur();
passwordRef.current.blur();

EDITED What difference does createref on the two fields have compared to using handlekeyup?

both works the same, when an event triggered,event.target is your target element, while React provide way to access dom element with createRef, there is no big difference with event.target and ref.current but its is good to use reference as using reference you can access element any where, no matter an event is occured or not

add this in your forms onSubmit

<Form
  onSubmitCapture={() => {
  if ("activeElement" in document) document.activeElement.blur();
  }}
>
...
</Form>

updated answer with form submit. Check the logs in console.

import React, { useState, useRef } from "react";

import "antd/dist/antd.css";
import { Form, Input, Button, Card } from "antd";

function Login() {
  const [loadings, setloadings] = useState(false);
  const [disabledLoading, setDisabledLoading] = useState(false);
  const formRef = useRef()
  function changeloading() {
    setloadings(true);
    setDisabledLoading(true);
    setTimeout(() => {
      setloadings(false);
    }, 1630);
  }

  function onFinish(values) {
    console.log(values)
  }
  function passwordEnterPress(e) {
    e.target.blur() 
    formRef.current.submit()
  }
  return (
    <div>
      <Card className="home-card">
        <Form ref={formRef} onFinish={onFinish}>
          <Form.Item name="Username">
            <Input name="username" />
          </Form.Item>
          <Form.Item name="Password">
            <Input.Password name="password" onPressEnter={passwordEnterPress} />
          </Form.Item>
          <Form.Item>
            <Button
              type="primary"
              htmlType="submit"
              onClick={() => changeloading()}
            >
              Log in
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
}

export default Login;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM