JSFiddle - React, Tailwind, and code Playground
by Alex Fogarty
HTML
<form action="#" method="post" id="contact-form">
<div>
<label for="name">Name:</label>
<input type="text" name="name" id="name" />
</div>
<div>
<label for="email">Email:</label>
<input type="text" name="email" id="email" />
</div>
<div>
<label for="message">Message:</label>
<textarea cols="40" rows="8" name="message" id="message"></textarea>
</div>
<div>
<button>Submit</button>
</div>
</form>
<div id="success">
<emphasis>Form submitted succesfully!</emphasis>
</div>
<div id="error">
<emphasis>All fields are required, please complete the form before submitting.</emphasis>
</div>
CSS
body{
font-family:arial;
padding:20px;
}
#error{
background-color:#f00;
color:#fff;
font-weight:bold;
font-size:18px;
width:300px;
text-align:center;
margin:20px auto;
padding:10px 0;
display:none; /* hide the error by default */
}
#success{
background-color:#0f0;
color:#fff;
font-weight:bold;
font-size:18px;
width:300px;
text-align:center;
margin:20px auto;
padding:10px 0;
display:none; /* hide the error by default */
}
input, textarea{
display:block;
margin-bottom:20px;
padding:5px 10px;
border-width:1px;
border-style:solid;
border-color:#555;
}
.hasError{
border-color:#f00;
}
JavaScript
$(document).ready(function() {
$("#contact-form").submit(function() {
validateForm();
});
// notice in the blur event I am using multiple selectors to target both the input AND the textarea ontrol
// the comma allows you to combine the results of TWO seperate selectors
$("input, textarea").blur(function() {
validateForm();
});
});
function validateForm() {
// standard routine to validate the form
}