How to process onChange and change focus to new <Field>? - javascript

I'm using Formik (with withFormik()) and want to check a <Field> as a user types in it - after it has 4 characters in it, I want to focus on the next field so they can keep typing without having to move to the next field.
So my InnerForm has:
<Field
type="text"
name="credit1"
inputmode="numeric"
maxlength="4" />
<Field
type="text"
name="credit2"
inputmode="numeric"
maxlength="4" />
And my FormikInnerFormContainer = withFormik(...) has a validationSchema.
How could I catch changes on the first field, and move focus to the 2nd field if the first has 4 characters in?
I tried to override the onChange, but couldn't figure out how to update the Field contents with each character the user types.

You might use like this in Formik.
focusChange(e) {
if (e.target.value.length >= e.target.getAttribute("maxlength")) {
e.target.nextElementSibling.focus();
}
...
//Example implementation
import React from "react";
import { Formik } from "formik";
export default class Basic extends React.Component {
constructor(props) {
super(props);
this.inputRef = React.createRef();
this.focusChange = this.focusChange.bind(this);
}
focusChange(e) {
if (e.target.value.length >= e.target.getAttribute("maxlength")) {
e.target.nextElementSibling.focus();
}
}
render() {
return (
<div>
<h1>My Form</h1>
<Formik
initialValues={{ name: "" }}
onSubmit={(values, actions) => {
setTimeout(() => {
alert(JSON.stringify(values, null, 2));
actions.setSubmitting(false);
}, 1000);
}}
render={props => (
<form onSubmit={props.handleSubmit} ref={this.inputRef}>
<input
type="text"
onChange={props.handleChange}
onBlur={props.handleBlur}
value={props.values.name}
name="name"
maxlength="4"
onInput={e => this.focusChange(e)}
/>
<input
type="text"
onChange={props.handleChange}
onBlur={props.handleBlur}
value={props.values.lastName}
name="lastName"
maxlength="4"
onInput={this.focusChange}
/>
<button type="submit">Submit</button>
</form>
)}
/>
</div>
);
}
}

In vanilla javascript you can do this:
document.querySelectorAll('input').forEach(function(input) {
input.addEventListener('keyup', function() {
if(input.value.length >= input.getAttribute('maxlength'))
input.nextElementSibling.focus();
});
})

Related

How to pre-populate fields on click of a button in react?

I am trying to pre-populate the form fields, that are replicated, from the fields that are already filled. On clicking the "Add fields" button, the fields are getting replicated. But I want them to get pre-populated using the data filled in the already existing fields.
From where can I get hold of the input values?
import './style.css';
export default function App() {
const [inputFields, setInputFields] = useState([{ name: '', age: '' }]);
const addFields = (e) => {
e.preventDefault();
let newField = { name: "", age: '' };
setInputFields([...inputFields, newField]);
};
const handleFormChange = (index, e) => {
let data=[...inputFields];
data[index][e.target.name]=[e.target.value];
setInputFields(data);
}
return (
<div>
<form>
{inputFields.map((input, index) => {
return (
<div key={index}>
<input
type="text"
name="name"
placeholder="Enter name"
value={input.name}
onChange={(e)=>handleFormChange(index, e)}
/>
<input
type="number"
name="age"
placeholder="Enter Age"
value={input.age}
onChange={(e)=>handleFormChange(index, e)}
/>
<br />
<br />
</div>
);
})}
<button onClick={addFields}>Add Field</button>
<br />
</form>
</div>
);
}```
You will need to track changes in input with an onChange handler.
Also, you are not setting values from the last input fields anywhere to be able to duplicate them. The below code might work as you expect:
const { useState } = React;
function App() {
const [inputFields, setInputFields] = useState([{ name: '', age: '' }]);
const addFields = (e) => {
e.preventDefault();
const temp = inputFields.slice()
, length = temp.length - 1
, { name, age } = temp[length]
// Set value from last input into the new field
let newField = { name, age }
setInputFields([...temp, newField])
}
, handleChange = (index, event) => {
const temp = inputFields.slice() // Make a copy of the input array first.
inputFields[index][event.target.name] = event.target.value // Update it with the modified values.
setInputFields(temp) // Update the state.
};
return (
<div>
<form>
{inputFields.map((input, index) => {
return (
<div key={index}>
<input
onChange={e => handleChange(index, e)}
value={input.name}
type="text"
name="name"
placeholder="Enter name"
/>
<input
onChange={e => handleChange(index, e)}
value={input.age}
type="number"
name="age"
placeholder="Enter Age"
/>
<br />
<br />
</div>
);
})}
<button onClick={addFields}>Add Field</button>
<br />
</form>
</div>
);
}
ReactDOM.render(
<App />,
document.getElementById("react")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="react"></div>
You have to set the value property on the input field to populate, e.g:
<input
value={input.name}
type="text"
name="name"
placeholder="Enter name"
/>

ReactJS event.target.value returns as undefined

I've made a form in ReactJS with one text input and when it submits I want to get its value and put it into a variable. But when I console.log() it returns as undefined. How do I fix this? Here is my code.
class App extends Component {
state = {
todoTitle: ""
};
render() {
return (
<div>
<center>
<form
onSubmit={(event) => {
event.preventDefault();
this.setState(todoTitle: event.target.value,);
console.log(this.state.todoTitle); // Returns "undefined"
}}
>
<input
type="text"
autocomplete="off"
class="form-control"
name="todoInput"
placeholder="Enter todo"
style={{ width: "400px", height: "50px" }}
/>
<input
type="submit"
value="Submit"
id="submitButton"
></input>
</form>
</center>
}
}
}
You need to either make a controlled input or useRef for un-controlled input for the React to keep track of your todoTitle state.
To make a controlled input, you will need to use onChange event and a value={this.state.todoTitle} property.
Also on your form, it is best to add an onSubmit event. There is however an option to set the submit on the form submit button also. In that case we need to use onClick={this.handleSubmit} as follows <input type="submit" value="Submit" id="submitButton" onClick={this.handleSubmit} />.
The below code will work for you:
class Form extends React.Component {
state = {
todoTitle: "",
};
handleSubmit = (e) => {
e.preventDefault();
console.log(this.state.todoTitle);
};
render() {
return (
<div>
<form onSubmit={this.handleSubmit}>
<input
type="text"
autocomplete="off"
class="form-control"
name="todoInput"
placeholder="Enter todo"
style={{ width: "400px", height: "50px" }}
value={this.state.todoTitle}
onChange={(e) => this.setState({ todoTitle: e.target.value })}
/>
<input type="submit" value="Submit" id="submitButton" />
</form>
</div>
);
}
}
You can modify your app a bit to get the value on onChange of input textfield, and then store it in the array in case of below example:
export default class App extends React.Component {
state = {
todoTitle: "",
todoList: []
};
render() {
return (
<div>
<center>
<form
onSubmit={event => {
event.preventDefault();
this.setState(
{
todoList: [...this.state.todoList, this.state.todoTitle]
},
() => {
console.log(this.state.todoList);
}
);
}}
>
<input
type="text"
autocomplete="off"
class="form-control"
name="todoInput"
placeholder="Enter todo"
onChange={event => {
this.setState({ todoTitle: event.target.value });
console.log(event.target.value);
}}
style={{ width: "400px", height: "50px" }}
/>
<input type="submit" value="Submit" id="submitButton" />
</form>
</center>
</div>
);
}
}
Full app here: Stackblitz
There are a few other errors with your code, but I will just answer your question.
setState triggers a re-render, so your state isn't available to log until the next time it runs. You can just log what you put in setState.
console.log(event.target.value);
This question has more info.
setState doesn't update the state immediately
Also, you can do a callback.
this.setState({ todoTitle: event.target.value }, () =>
console.log(this.state.todoTitle)
);
Try this:
class App extends React.Component {
constructor(props) {
super(props);
this.state = { todoTitle: "" };
this.handleSubmit = this.handleSubmit.bind(this);
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
event.preventDefault();
this.setState({ todoTitle: event.target.value });
}
handleSubmit(event) {
event.preventDefault();
console.log(this.state.todoTitle);
}
render() {
return (
<div>
<center>
<form onSubmit={this.handleSubmit}>
<input
type="text"
autocomplete="off"
class="form-control"
name="todoInput"
placeholder="Enter todo"
style={{ width: "400px", height: "50px" }}
onChange={this.handleChange}
/>
<input type="submit" value="Submit" id="submitButton" />
</form>
</center>
</div>
);
}
}
This will change the state on input changes and then logs on submit the state. An alternative would be to just get the input element and its value via getElementById or something similar in React.
Your code was also not very well formatted and a lot of closing tags missed.
Read more here:
Get form data in ReactJS

Can't uncheck checkbox using react

This checkbox is permanently checked, I want the pre selected checkbox to change the boolean state. I'm currently using this handleChange method to deal with text inputs. Do I have to create another method to deal with the checkbox or can I add to the existing method?
state = {
billingEmail:'',
billingAddressSame: true,
}
handleChange = input => e => {
this.setState({[input]: e.target.value})
}
<input
className="col-sm-12"
type="email"
placeholder="Email"
onChange={handleChange('billingEmail')}
defaultValue={values.billingEmail}
/>
<label className="col-sm-12" style={{paddingLeft: "0"}}>
<input
type="checkbox"
checked={values.billingAddressSame}
onChange={handleChange('billingAddressSame')}
/>
Same as company address
</label>
Change your handleChange function to
handleChange = input => e => {
this.setState({[input]: !this.state[input]})
}
You can control your checkbox and input by a single method.
See
Constructor and handle change function-
constructor(props) {
super(props);
this.state = {
isGoing: true,
numberOfGuests: 2
};
this.handleInputChange = this.handleInputChange.bind(this);
}
handleInputChange(event) {
const target = event.target;
const value = target.type === 'checkbox' ? target.checked : target.value;
const name = target.name;
this.setState({
[name]: value
});
}
And in your render function -
render() {
return (
<form>
<label>
Is going:
<input
name="isGoing"
type="checkbox"
checked={this.state.isGoing}
onChange={this.handleInputChange} />
</label>
<label>
Number of guests:
<input
name="numberOfGuests"
type="number"
value={this.state.numberOfGuests}
onChange={this.handleInputChange} />
</label>
</form>
);
}
See this for more info
try this and let me know, its working fine for me
import React, { Component, Fragment } from 'react';
class SignUp extends Component{
state = {
billingEmail:'',
billingAddressSame: true,
}
render(){
return(<Fragment>
<input className="input" type="email" className="col-sm-12" placeholder="Email" value={this.state.billingEmail} onChange={e => this.setState({billingEmail: e.target.value})}/>
<label className="col-sm-12" style={{paddingLeft: "0"}}>
<input type="checkbox" value="CheckBox1" checked={this.state.billingAddressSame} onChange={e => this.setState({ billingAddressSame: !this.state.billingAddressSame })} />
Same as company address
</label>
</Fragment>)
}
}
export default SignUp;

Storing each input's data in its respective state

I have three inputs, and I want each input's data to be stored in a state. For example, the name input should be stored in the name state, because I'll need it later to push the three states' values in a firebase database.
I used the onChange function to store the data, but I didn't know how to make each input's function relative to the state I want to put it in.
import React from "react";
import ReactDOM from "react-dom";
export default class Inputs extends React.Component {
constructor(props) {
super(props);
this.state = {
name: "",
email: "",
age: ""
};
}
handleChange = e => {
this.setState({ name: e.target.value });
};
render() {
return (
<div>
<form>
<label>
name:
<input type="text" name="name" onChange={this.handleChange} />
</label>
<label>
email:
<input type="text" name="email" onChange={this.handleChange} />
</label>
<label>
age:
<input type="text" name="age" onChange={this.handleChange} />
</label>
<input type="submit" value="Submit" />
</form>
<textarea value={this.state.value} onChange={this.handleChange} />
<button onClick={() => this.props.onClick(this.state.value)}>
Add task
</button>
</div>
);
}
}
getChanges = (e) => {
console.log(e);
this.setState({[e.target.name]: e.target.value}, function () {
console.log(this.state)
})
};
call this function,
<Input onChange={(e) => this.getChanges(e)} name={'name'}
value={this.state.name} placeholder={'Name'}/>
You can pass key and value
<input type="text" name="name" onChange={(event)=>this.handleChange(event,'name')} />
and in your function you can do something like this
handleChange = (e,key) => {
this.setState({ [key] : e.target.value });
};

Need to get the multiple form elements in uncontrolled components in reactjs

i am trying to get the multiple form fields input values and sending that to server. But i am only able to get the last field's value on submit.
I am using uncontrolled component because i am trying to editing the form and then updating it.Please help me out to get all the form details entered in the form.
import React from 'react';
import axios from 'axios';
class Update extends React.Component {
constructor(props) {
super(props);
this.state = {
info:''
};
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(event) {
event.preventDefault();
console.log(event);
alert(event);
}
componentDidMount(){
let self = this;
axios.get('http://localhost:8080/studentById')
.then(function(data) {
//console.log(data);
self.setState({info:data.data});
});
}
render() {
return (
<div>
<form onSubmit={this.handleSubmit} >
<label className="w3-label w3-text-blue w3-large w3-margin-0 ">
First Name:
<input autoFocus type="text" className="w3-input w3-border" defaultValue={this.state.info.Firstname} ref={(input) => this.input = input} required />
</label>
<label className="w3-label w3-text-blue w3-large">
Last Name:
<input type="text" className="w3-input w3-border" defaultValue={this.state.info.Lastname} ref={(input) => this.input = input} required />
</label>
<input className="w3-btn-block w3-blue w3-margin-bottom w3-large" type="submit" value="Submit" />
</div>
)};
}
In your code, you assign all refs to the same variable. (your code simplified for showing what I mean)
First Name:
<input ref={(input) => this.input = input} />
Last Name:
<input ref={(input) => this.input = input} />
Instead use different variable for different input fields:
First Name:
<input ref={(input) => this.firstNameInput = input} />
Last Name:
<input ref={(input) => this.lastNameInput = input} />
You should use different property names for each input inside refs callbacks (currently you override this.input so it points to the last input):
<input autoFocus type="text" className="w3-input w3-border" defaultValue={this.state.info.Firstname} ref={(input) => this.input1 = input} required />
<input autoFocus type="text" className="w3-input w3-border" defaultValue={this.state.info.Firstname} ref={(input) => this.input2 = input} required />
Then inside your component methods you can access value of an input this way:
let inputValue = this.input1.value;

Categories