HTML preprocessors can make writing HTML more powerful or convenient. For instance, Markdown is designed to be easier to write and read for text documents and you could write a loop in Pug.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. So you don't have access to higher-up elements like the <html>
tag. If you want to add classes there that can affect the whole document, this is the place to do it.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. If you need things in the <head>
of the document, put that code here.
The resource you are linking to is using the 'http' protocol, which may not work when the browser is using https.
CSS preprocessors help make authoring CSS easier. All of them offer things like variables and mixins to provide convenient abstractions.
It's a common practice to apply CSS to a page that styles elements such that they are consistent across all browsers. We offer two of the most popular choices: normalize.css and a reset. Or, choose Neither and nothing will be applied.
To get the best cross-browser support, it is a common practice to apply vendor prefixes to CSS properties and values that require them to work. For instance -webkit-
or -moz-
.
We offer two popular choices: Autoprefixer (which processes your CSS server-side) and -prefix-free (which applies prefixes via a script, client-side).
Any URLs added here will be added as <link>
s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.
You can apply CSS to your Pen from any stylesheet on the web. Just put a URL to it here and we'll apply it, in the order you have them, before the CSS in the Pen itself.
You can also link to another Pen here (use the .css
URL Extension) and we'll pull the CSS from that Pen and include it. If it's using a matching preprocessor, use the appropriate URL Extension and we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
JavaScript preprocessors can help make authoring JavaScript easier and more convenient.
Babel includes JSX processing.
Any URL's added here will be added as <script>
s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.
You can apply a script from anywhere on the web to your Pen. Just put a URL to it here and we'll add it, in the order you have them, before the JavaScript in the Pen itself.
If the script you link to has the file extension of a preprocessor, we'll attempt to process it before applying.
You can also link to another Pen here, and we'll pull the JavaScript from that Pen and include it. If it's using a matching preprocessor, we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
Search for and use JavaScript packages from npm here. By selecting a package, an import
statement will be added to the top of the JavaScript editor for this package.
Using packages here is powered by esm.sh, which makes packages from npm not only available on a CDN, but prepares them for native JavaScript ESM usage.
All packages are different, so refer to their docs for how they work.
If you're using React / ReactDOM, make sure to turn on Babel for the JSX processing.
If active, Pens will autosave every 30 seconds after being saved once.
If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.
If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.
Visit your global Editor Settings.
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Intro to Form Validtion</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
<link rel="stylesheet" href="./style.css">
</head>
<body>
<main class="container main">
<div id="form-submitted-msg">Form successfully submitted!</div>
<form id="exampleForm" novalidate>
<div class="input-group">
<label for="firstName" class="form-label">First name </label>
<input type="text" id="firstName" name="firstName" class="form-control" required>
<small class="error-msg invalid-feedback">Required</small>
</div>
<div class="input-group">
<label for="lastName" class="form-label">Last name </label>
<input type="text" id="lastName" name="lastName" class="form-control" required>
<small class="error-msg invalid-feedback">Required</small>
</div>
<div class="input-group">
<label for="email" class="form-label">Email </label>
<input type="email" id="email" name="email" class="form-control" required>
<small class="error-msg invalid-feedback">Required</small>
</div>
<div class="input-group">
<label for="password" class="form-label">Password </label>
<input type="password" id="password" name="password" class="form-control" required>
<small class="error-msg invalid-feedback">Required</small>
</div>
<div class="input-group select">
<label for="password" class="form-label">Select Account Type </label>
<select id="accountType" name="accountType" class="form-select" required>
<option value="Please select an option" selected class="text-muted">Please select an option</option>
<option value="Free Account">Free Account</option>
<option value="Premium Account">Premium Account</option>
</select>
<small class="error-msg invalid-feedback">Required</small>
</div>
<div class="input-group radio">
<div class="form-check">
<input type="radio" id="personal" name="purpose" value="Personal" class="form-check-input" required>
<label for="personal" class="form-check-label">Personal</label>
<small class="error-msg invalid-feedback">Required</small>
</div>
<div class="form-check">
<input type="radio" id="business" name="purpose" value="Business" class="form-check-input" required>
<label for="business" class="form-check-label">Business</label>
<small class="error-msg invalid-feedback">Required</small>
</div>
</div>
<div class="input-group checkbox form-check">
<input type="checkbox" name="subscribe" id="subscribeYes" class="form-check-input" required>
<label for="subscribeYes" class="form-check-label">Subscribe to our newsletter?</label>
<small class="error-msg invalid-feedback">Required</small>
</div>
<div class="form-btns">
<button type="submit" class="btn btn-primary submit" disabled>SUBMIT</button>
<button type="reset" class="btn btn-secondary">CLEAR FORM</button>
</div>
</form>
</main>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYXK/7HAuoJl+0I4" crossorigin="anonymous"></script>
<script src="./main.js"></script>
</body>
</html>
*, *::before, *::after {
box-sizing: border-box;
margin: 0;
padding: 0;
}
.main {
width: 100%;
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
}
#form-submitted-msg {
margin-bottom: 3rem;
border-radius: 3px;
background-color: rgb(67, 161, 67);
padding: 0.5rem;
width: 40%;
text-align: center;
color: #fff;
display: none;
}
#exampleForm {
width: 40%;
}
.input-group {
margin-bottom: 1.5rem;
}
.input-group:not(.radio):not(.checkbox) {
gap: 0.25rem;
flex-direction: column;
}
.input-group:not(.radio):not(.checkbox) input {
width: 100%;
border-radius: 0.375rem !important;
}
.input-group.checkbox {
gap: 1rem;
}
.input-group.radio {
display: flex;
gap: 1.5rem;
width: 100%;
}
.input-group.select select {
width: 100%;
}
legend {
font-size: 1rem;
width: max-content;
}
.form-btns {
display: flex;
width: 100%;
gap: 1rem;
margin-top: 2.5rem;
}
.form-btns > button {
padding: 0.3rem 1.5rem;
}
.form-btns > .submit {
padding-inline: 3rem;
}
.error-msg {
display: none;
}
// Write your code here
// Get all the necessary DOM elements
const form = document.getElementById('exampleForm')
const submitButton = document.querySelector('.submit')
const successMessage = document.getElementById('form-submitted-msg')
// Store all form elements in an array by spreading the elements property of the form
const formElements = [ ...form.elements ]
// Create function to check if all form elements are valid
const allInputsValid = () => {
const valid = formElements.every((element) => {
if (element.nodeName === 'SELECT') {
return element.value !== 'Please select an option'
} else {
return element.checkValidity()
}
})
return valid
}
// Define a function to handle changes to any form element
const handleChange = () => {
// Use the forEach() function to execute the provided function once for each element in the formElements array
formElements.forEach((element) => {
// If the element is invalid and is not a button, a select dropdown, a checkbox, or a radio button, style it with a red border and red text
if (!element.checkValidity()
&& element.nodeName !== 'BUTTON'
&& element.nodeName !== 'SELECT'
&& element.type !== 'checkbox'
&& element.type !== 'radio'
) {
element.style.borderColor = 'red'
element.nextElementSibling.style.color = 'red'
element.nextElementSibling.style.display = 'block'
element.previousElementSibling.style.color = 'red'
}
// If the element is valid, reset its style to the original colors
// The conditions are the same as above for excluding certain elements
if (element.checkValidity()
&& element.nodeName !== 'BUTTON'
&& element.nodeName !== 'SELECT'
&& element.type !== 'checkbox'
&& element.type !== 'radio'
) {
element.style.borderColor = '#CED4DA'
element.nextElementSibling.style.color = '#CED4DA'
element.nextElementSibling.style.display = 'none'
element.previousElementSibling.style.color = '#212529'
}
// If the element is a checkbox or a radio button and is invalid, style it with a red border and red text
if (!element.checkValidity()
&& (element.type === 'checkbox'
|| element.type === 'radio')
) {
element.style.borderColor = 'red'
element.nextElementSibling.style.color = 'red'
}
// If the checkbox or radio button is valid, reset its style to the original colors
if (element.checkValidity()
&& (element.type === 'checkbox'
|| element.type === 'radio')
) {
element.style.borderColor = '#CED4DA'
element.nextElementSibling.style.color = '#212529'
}
// If the element is a select dropdown and the default option is selected, style it with a red border and red text
if (element.nodeName === 'SELECT'
&& element.value === 'Please select an option'
) {
element.style.borderColor = 'red'
element.nextElementSibling.style.color = 'red'
element.nextElementSibling.style.display = 'block'
element.previousElementSibling.style.color = 'red'
}
// If an option other than the default is selected in the dropdown, reset its style to the original colors
if (element.nodeName === 'SELECT'
&& element.value !== 'Please select an option'
) {
element.style.borderColor = '#CED4DA'
element.nextElementSibling.style.color = '#CED4DA'
element.nextElementSibling.style.display = 'none'
element.previousElementSibling.style.color = '#212529'
}
})
// If all form elements are valid, enable the submit button; otherwise, disable it
if (allInputsValid()) {
submitButton.removeAttribute('disabled', '')
} else {
submitButton.setAttribute('disabled', '')
}
}
// Define a function to handle form submission
const handleSubmit = (e) => {
// Prevent the default form submission behavior
e.preventDefault()
// If all form elements are valid after the form submission, display a success message, reset the form, and disable the submit button
if (allInputsValid()) {
successMessage.style.display = 'block'
form.reset()
submitButton.setAttribute('disabled', '')
// Hide the success message after 3 seconds
setTimeout(() => {
successMessage.style.display = 'none'
}, 3000)
}
}
// Add event listener to each form element
formElements.forEach((element) => {
element.addEventListener('change', handleChange)
})
// Add submit listener to the form
form.addEventListener('submit', (e) => handleSubmit(e))
Also see: Tab Triggers