Javascript Remove Focus on Enter Key Press - javascript

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.

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

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;

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;

Related

React From Group input field is not working

I attached dropdown items to my form group input field (image below). When I add onChange() key in order to get its value, I cannot write anything to input field. But when I remove onChange() key, it is working, I am able to write anything, but I need to get the value of input field. Is there any other way than onChange() key or any solution? Thank you in advance :)
Here is the my code:
<Form.Control
ref={ref}
onClick={e => {
e.preventDefault();
onClick(e);
}}
size="sm"
type="text"
className="search-or-jump shadow-none"
placeholder="Search or jump to..."
onChange={event => setSearchName(event.target.value)}
/>
{children}
</Form.Group>
You have to add value attributes, like
<Form.Control
ref={ref}
onClick={e => {
e.preventDefault();
onClick(e);
}}
size="sm"
type="text"
className="search-or-jump shadow-none"
placeholder="Search or jump to..."
value={searchName}
onChange={event => setSearchName(event.target.value)}
/>
{children}
</Form.Group>
Your code didn't have value attribule but you called 'value' on 'onChange' that why your code didn't work.

React final form - submit a wizard form on click of a radio button

I would like to submit a step of wizard form on click of radio button instead of classic submit button.
Radio component :
const Radio = ({ input, children }) => (
<label className="form-radio city">
<input {...input} />
<span className="radio-text">{children}</span>
</label>
)
My class :
<ProfileForm.Page>
{CITIES.map(({ name }) => (
<Field component={Radio} type="radio" name="city" key={name} value={name}>
{name}
</Field>
))}
<button type="submit"></button>
</ProfileForm.Page>
This worked when I use the submit button but I want to remove it and submit city directly on click on the radio button.
I tried to had an onChange event with "this.form.submit()" but I cannot acced to "form".
I have a parent component ProfileForm.jsx with :
<Form validate={this.validate} onSubmit={this.handleSubmit} initialValues={values}>
{({ handleSubmit, invalid, pristine, values }) => (
<form onSubmit={handleSubmit}>
{activePage}
</form>
)}
</Form>
and my radio buttons are on the "active page" City.jsx with the code of my first post

Add 'keydown' event listener to document except for input field

I am creating a Hangman game with a virtual keypad and a form input section where users can guess the entire word.
I am able to add a 'keydown' event listener to the document, but I DO NOT want want the 'keydown' event to fire off if I am typing into the input field.
Here is how I've added the event listener.
document.addEventListener('keydown', handleKeyDown);
Here is the form input.
<form onSubmit={e => onSubmit(e)}>
<div className="input-group">
<input
type="text"
className="form-control"
name="letter"
placeholder="Guess the word"
value={formWord}
onChange={e => setFormWord(e.target.value.toUpperCase())}
disabled={disabled}
/>
<div className="input-group-append">
<button
className="btn text-white"
type="submit"
disabled={disabled}
>
<i className="far fa-arrow-alt-circle-right" /> Go!
</button>
</div>
</div>
</form>
I've already tried using document.getElementsByTagName[0].removeEventListener('keydown', handleKeyDown), but that's not working. I'm assuming that's because the event listener was added onto the actual document instead of the element.
Please help!
Inside handleKeyDown, only execute the body of the function if the event.target does not match the input field, eg:
const handleKeyDown = (event) => {
if (event.target.matches('[name="letter"]')) {
return;
}
// rest of function body
};

Generate element from submit React.js

I'd like to generate some HTML to show sucessfull form submission. I can't seem to do it within the handleSubmit Method.
class BookingForm extends Component{
...
handleChange(event) {
const target = event.target;
const value = target.value;
const name = target.name;
console.log(name + ' '+value);
this.setState({
[name]: value
});
}
Submit method that I'd like to render html:
handleSubmit(event) {
console.log(this.state.lessonTime)
event.preventDefault();
this.setState({'success':true})
return(
<h1>Success</h1>
);
}
render() {
return (
<div>
<form onSubmit={this.handleSubmit}>
<TimeList defaultTime={this.state.defaultTime}
handleChange={this.handleChange}/>
<br/>
<DateList defaultDate={this.state.defaultDate}
handleChange={this.handleChange}/>
<br/>
<NumberOfLessons defaultNOL={this.state.defaultLessons}
handleChange={this.handleChange}/>
<br/>
<input type="submit" value="Book Lesson" />
</form>
<br/>
</div>
);
}
}
Any ideas on how I can get the success heading to show once submit has been clicked on.
Thanks
I think a better way to handle this is to use state to control the rendering of "success" heading. You can add the following line of code to the place you want to add the header:
{this.state.success && <div> Successful </div> }
I think the reason the html tag returned by handleSubmit in your function doesn't show up is because although it returns the tag, it doesn't know where to put it. If you want to make it work, you'll need to use methods like createElement and appendChild but that's not the way react should work.
If you want your <h1> element to render instead of form on successful completion do this in your render function:
render() {
return (
<div>
{this.state.success?(
<h1>Success</h1>
):(
<form onSubmit={this.handleSubmit}>
<TimeList defaultTime={this.state.defaultTime}
handleChange={this.handleChange}/>
<br/>
<DateList defaultDate={this.state.defaultDate}
handleChange={this.handleChange}/>
<br/>
<NumberOfLessons defaultNOL={this.state.defaultLessons}
handleChange={this.handleChange}/>
<br/>
<input type="submit" value="Book Lesson" />
</form>
<br/>)}
</div>
);
}

Submit Form using Button in Parent Component in React

So I have to implement a form in modal, as you can see, the button in the modal are not the buttons in the form. I created the form as a child component of the modal. How can I submit the form using the button in the parent component. I am using React Semantic-UI react as my UI framework.
I think if I can hide the button in the form and trigger it using JavaScript. I think this might be achieved via getElementById, but is there a react way of doing it?
My current Modal looks like this:
<Modal open={this.props.open} onClose={this.props.onClose} size="small" dimmer={"blurring"}>
<Modal.Header> Edit Activity {this.props.name} </Modal.Header>
<Modal.Content>
<ActivityInfoForm/>
</Modal.Content>
<Modal.Actions>
<Button negative onClick={this.props.onClose}>
Cancel
</Button>
<Button positive
content='Submit'
onClick={this.makeActivityInfoUpdateHandler(this.props.activityId)} />
</Modal.Actions>
</Modal>
My form code looks like this:
<Form>
<Form.Group widths='equal'>
<Form.Input label='Activity Name' placeholder='eg. CIS 422' />
<Form.Input label='Activity End Date' placeholder='Pick a Date' />
</Form.Group>
<Form.Group widths='equal'>
<Form.Input label='Total Capacity' placeholder='eg. 30' />
<Form.Input label='Team Capacity' placeholder='eg. 3' />
</Form.Group>
</Form>
The simplest solution would be to use HTML form Attribute
Add "id" attribute to your form: id='my-form'
<Form id='my-form'>
<Form.Group widths='equal'>
<Form.Input label='Activity Name' placeholder='eg. CIS 422' />
<Form.Input label='Activity End Date' placeholder='Pick a Date' />
</Form.Group>
<Form.Group widths='equal'>
<Form.Input label='Total Capacity' placeholder='eg. 30' />
<Form.Input label='Team Capacity' placeholder='eg. 3' />
</Form.Group>
</Form>
Add the appropriate "form" attribute to the needed button outside of the form: form='my-form'
<Button positive form='my-form' content='Submit' value='Submit' />
What does your makeActivityInfoUpdateHandler function look like?
I assume you did it by the following way, and just continue adding more code to make it work for you:
1/ Add ref to your Form, then you can access the Form in the parent (Modal):
<Modal>
<Modal.Content>
<ActivityInfoForm ref="activityForm" />
</Modal.Content>
</Modal>
2/ Then in the makeActivityInfoUpdateHandler function:
makeActivityInfoUpdateHandler = (activityId) => {
// ...
this.refs.activityForm.getWrappedInstance().submit();
// ...
}
The above code is the way you should do, please post here some more details in case this doesn't work yet!
===========
EDITED VERSION BELOW: (after discussion with the author, and we together found a good way around!):
The idea now is put the ref on a button (this button has type="submit", and it belongs to the form), then when the button outside is clicked, we just need to call the "click()" function of the ref button [which is a smart thinking from the author himself]
(Actually, component from semantic-ui is a modified and improved version, no longer the standard form, so my previous way above may not work when it tries to submit the form, however, the below way will work)
The code will now look like:
1/ Add ref to the button on the form:
<Form onSubmit={ this.handleSubmit} >
<button style={{}} type='submit' ref={ (button) => { this.activityFormButton = button } } >Submit</button>
</Form>
2/ Then in the makeActivityInfoUpdateHandler function, trigger click() of the above button:
makeActivityInfoUpdateHandler = (activityId) => {
// ...
this.activityFormButton.click();
// ...
}
The selected answer was useful. But the method in it doesn't seem to work any longer. Here's how I went about it.
You can give a ref to the child component when it is being created.
<ChildComponent ref={this.childComponent}/>
And use it in the button's onClick method. (This is the code for the button)
<Button variant= "light" onClick={this.onClick}>
Submit
</Button>
(This is the onClick method)
onClick = (event) => {
this.childComponent.current.handleSubmit(event);
}
I'm calling a method in the child component called handleSubmit. It can look like this.
handleSubmit = (event)=> {
event.preventDefault();
//Your code here. For example,
alert("Form submitted");
}

Categories