<html>
<head>
<meta charset="UTF-8" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.26.0/babel.min.js"></script>
</head>
<body>
<div id="app"></div>
<script type="text/babel">
const { useState } = React;
function App() {
const [formValues, setFormValues] = useState({
field1: '',
field2: '',
nonRequiredField: '',
});
// Check if any of the required fields are empty
const isSubmitDisabled = !(formValues.field1 && formValues.field2);
const handleInputChange = (event) => {
const { name, value } = event.target;
setFormValues({
...formValues,
[name]: value,
});
};
const handleSubmit = (event) => {
event.preventDefault();
// Handle form submission logic here
};
return (
<div className='container'>
<h3>React Js Disable submit Button if required fields are Empty </h3>
<form onSubmit={handleSubmit}>
<label>
Field 1 (Required):
<input
type="text"
name="field1"
value={formValues.field1}
onChange={handleInputChange}
required
/>
</label>
<label>
Field 2 (Required):
<input
type="text"
name="field2"
value={formValues.field2}
onChange={handleInputChange}
required
/>
</label>
<label>
Non-Required Field:
<input
type="text"
name="nonRequiredField"
value={formValues.nonRequiredField}
onChange={handleInputChange}
/>
</label>
{/* Add more input fields for other required or non-required fields if needed */}
<button type="submit" disabled={isSubmitDisabled}>
Submit
</button>
</form>
</div>
);
}
ReactDOM.render(<App />, document.getElementById('app'));
</script>
<style>
/* Container */
.container {
font-family: Arial, sans-serif;
max-width: 800px;
margin: 0 auto;
padding: 20px;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
text-align: center;
}
form {
display: flex;
flex-direction: column;
}
label {
margin-bottom: 10px;
font-weight: bold;
}
input[type="text"] {
padding: 10px;
border: 1px solid #ccc;
border-radius: 3px;
margin-top: 5px;
font-size: 16px;
}
button[type="submit"] {
background-color: #007BFF;
color: #fff;
border: none;
border-radius: 3px;
padding: 10px 15px;
font-size: 16px;
cursor: pointer;
transition: background-color 0.3s;
}
/* Disable button */
button[type="submit"]:disabled {
background-color: #ccc;
/* Change this to your desired disabled button color */
cursor: not-allowed;
}
button[type="submit"]:hover {
background-color: #0056b3;
}
/* You can add more custom styles as needed */
/* Style the required field indicator */
input:required::after {
content: '*';
color: red;
margin-left: 5px;
}
/* Style error messages */
input:invalid {
border-color: red;
}
/* Style the form when it's in an error state */
form:invalid {
border-color: red;
}
</style>
</body>
</html>