React JS - disable a button if the input field is empty?
It's a common mistake coming from Class Components, state setter in hooks does not merge state value as in classes.
You initialized your state as a string (useState('')
) and then assigned it as an object
const autoComplete = (e) => {
setText({ value: e.target.value });
};
// State is an object { value: 'some text' }
Fix your set state call:
const autoComplete = (e) => {
setText(e.target.value);
};
// State is a string 'some text'
Then to be more verbose you want to check if the string is empty:
<button disabled={text === ''}>find</button>
How to disable a button when an input is empty?
You'll need to keep the current value of the input in state (or pass changes in its value up to a parent via a callback function, or sideways, or <your app's state management solution here> such that it eventually gets passed back into your component as a prop) so you can derive the disabled prop for the button.
Example using state:
<meta charset="UTF-8"><script src="https://fb.me/react-0.13.3.js"></script><script src="https://fb.me/JSXTransformer-0.13.3.js"></script><div id="app"></div><script type="text/jsx;harmony=true">void function() { "use strict";
var App = React.createClass({ getInitialState() { return {email: ''} }, handleChange(e) { this.setState({email: e.target.value}) }, render() { return <div> <input name="email" value={this.state.email} onChange={this.handleChange}/> <button type="button" disabled={!this.state.email}>Button</button> </div> }})
React.render(<App/>, document.getElementById('app'))
}()</script>
Disable submit button if field is empty
If you want to disable a button when an input string is empty, then the only state you need is the value of the input string.
const [inputVal, setInputVal] = useState('')
// ...
<input value={inputVal} onChange={e => setInputVal(e.target.value)} />
// ...
<button disabled={!inputVal}> /* ... */ </button>
Here we connect the input component to the state value. This is called a controlled component, because its value is controlled from by an external source (the state value) as opposed to an uncontrolled component, which means the input element holds it's own internal state (the default way inputs work if you don't set their value
prop directly.
When the input component receives input (such as someone typing a character) the onChange
prop is called. All we do then is take the new value of the input element (e.target.value
) and use it to set the state.
If you can derive state from other state, then you shouldn't be storing it in state. Having a state variable called disabled
only makes things more complex. The general idea is to use as little state as possible, and compute as much as you can from that state.
How to disable submit input field until all required fields and checkboxes are empty
You can apply the required
attribute to your inputs. When one of the inputs in a form has this attribute but has not been filled at the moment the Submit button is clicked, the form will not be submitted. Instead, the invalid
event will be fired on all inputs whose values are missing. You can use it to let the user know what needs to be filled in.
Here is a minimal example using React:
const { useState } = React;
function Input(props) {
const [invalid, setInvalid] = useState(false);
const handleInvalid = event => {
event.preventDefault();
console.log('Invalid');
setInvalid(true);
};
const handleChange = () => setInvalid(false);
const className = invalid ? 'invalid' : '';
return (
<div className={className}>
<input {...props} onInvalid={handleInvalid} onChange={handleChange} />
{props.type === "checkbox" && (
<label htmlFor={props.id}>
{props.label}
</label>
)}
</div>
);
}
function Form() {
const handleSubmit = event => {
event.preventDefault();
console.log('Submit');
};
return (
<form onSubmit={handleSubmit}>
<Input name="name" placeholder="Name" required />
<Input type="checkbox" name="accept" id="accept" label="I accept Terms of Usage" required />
<button>Submit</button>
</form>
);
}
ReactDOM.render(<Form />, document.getElementById('root'));
.invalid input[type=text], .invalid input:not([type]) {
border: 2px solid red;
}
.invalid label {
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="root"></div>
Enable Disabled Button if Input is not empty
Id propose something like this
- Use a block, which encapsulates the names of variables and functions inside the block scope
- Make small functions, which do just one thing
- Prefer
addEventListener
overonclick
oronanything
- There are two types of events you could use on the
input
s:input
andchange
.input
will react on every keystroke,check
will only react, if you blur theinput
element - I added a check for validity to the email field with
checkValidity
method{
const btn = document.getElementById("submit-btn");
const fname = document.getElementById("fname");
const email = document.getElementById("email");
deactivate()
function activate() {
btn.disabled = false;
}
function deactivate() {
btn.disabled = true;
}
function check() {
if (fname.value != '' && email.value != '' && email.checkValidity()) {
activate()
} else {
deactivate()
}
}
btn.addEventListener('click', function(e) {
alert('submit')
})
fname.addEventListener('input', check)
email.addEventListener('input', check)
}<form>
<input type="text" name="" id="fname">
<input type="email" name="" id="email">
<input type="submit" id="submit-btn" value="Submit">
</form>Disable Button when input is empty in react
You could just do it like
<form onSubmit={this.props.addCourse}>
<input onKeyUp={() => success()} id='id' value={this.props.value} type='text' onChange={this.props.updateCourse} />
<button disabled={this.props.value === ""} id="button" type='submit'>Add Course</button>
//added condition to button disabled property
</form>If the value of
this.props.value
is empty it would return true and hence button will be disabled.React - Disable button in Ant Design form until all required fields are filled
Check the following example using
onValuesChange
method ofForm
componentimport React, { useState } from 'react';
import 'antd/dist/antd.css';
import './index.css';
import { Form, Input, Button, Checkbox } from 'antd';
const Demo = () => {
const [btndisabled, setbtndisabled] = useState(true);
const onFinish = (values) => {
console.log('Success:', values);
};
const onFinishFailed = (errorInfo) => {
console.log('Failed:', errorInfo);
};
const onValuesChange = (changedValues, allValues) => {
if ( allValues.username != undefined && allValues.password != undefined && allValues.username != '' && allValues.password != '') {
setbtndisabled(false);
} else {
setbtndisabled(true);
}
console.log(allValues);
};
return (
<Form
name="basic"
labelCol={{
span: 8,
}}
wrapperCol={{
span: 16,
}}
initialValues={{
remember: true,
}}
onFinish={onFinish}
onValuesChange={onValuesChange}
onFinishFailed={onFinishFailed}
>
<Form.Item
label="Username"
name="username"
rules={[
{
required: true,
message: 'Please input your username!',
},
]}
>
<Input />
</Form.Item>
<Form.Item
label="Password"
name="password"
rules={[
{
required: true,
message: 'Please input your password!',
},
]}
>
<Input.Password />
</Form.Item>
<Form.Item
wrapperCol={{
offset: 8,
span: 16,
}}
>
<Button disabled={btndisabled} type="primary" htmlType="submit">
Submit
</Button>
</Form.Item>
</Form>
);
};Screenshot:
Before entering all values
After entering all values
Related Topics
Get Docx File Contents Using Javascript/Jquery
Button Enabled and Disabled Based on Checkbox Is Checked or Not
Javascript Generate Random Numbers Without Repeating
Keep Order of Objects Inside a Json String After They Are Parsed
How to Take Screenshot of a Div With JavaScript
Escaping Apostrophe (Single Quote) Character in JavaScript and HTML
Converting User Input String to Regular Expression
Javascript Regex Splitting Words in a Comma Separated String
Possible to Detect If a User Has Multiple Tabs of Your Site Open
Get Request Works With Postman But Why Doesn't It Work With Reactjs Fetch
How to Get the Id of a Button That Was Clicked - Reactjs
How to Post Selected Values Using Ajax
How to Attach Multiple Images in a Embed
Whenever I Click Outside the Element It Should Close
How to Set Top and Bottom Margin in Addhtml