I'm doing contact form by passing value dynamically for all inputs fields.i have two forms on the same page using id i passed values. In js same code for these two forms. The problem is after passing correct value also it is showing an error and if I submit form1 then form2 also getting submitted. Here validations are not working I tried everything is correct what might be the problem.
$(document).ready(function() {
/* contact form tabs*/
function button() {
$('.demos-nav .iva-nav').click(function() {
var btn = $(this).data('btn');
$('.row').removeClass('current').css('display', 'none');
$('.demos-nav .iva-nav').removeClass('current');
$(this).addClass('current');
$("#" + btn).addClass('current').css('display', 'block');
})
}
button();
/* name*/
$("[class^='form_']").on('input', function() {
var input = $(this);
var is_name = input.val();
if (is_name) {
input.removeClass("invalid").addClass("valid");
} else {
input.removeClass("valid").addClass("invalid");
}
});
/* E-mail */
$("[class^='form_']").on('input', function() {
var input = $(this);
var regex = /^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/;
var is_email = regex.test(input.val());
if (is_email) {
input.removeClass("invalid").addClass("valid");
} else {
input.removeClass("valid").addClass("invalid");
}
});
/* Phone */
$("[class^='form_']").on('input', function() {
var input = $(this);
var regex = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
var is_phone = regex.test(input.val());
if (is_phone) {
input.removeClass("invalid").addClass("valid");
} else {
input.removeClass("valid").addClass("invalid");
}
});
/* select People*/
$("[class^='form_']").change(function() {
var select = $(this);
var selectOption = $("#contact_select option:selected").val();
if (selectOption) {
select.removeClass("invalid").addClass("valid");
} else {
select.removeClass("valid").addClass("invalid");
}
});
/* select Time*/
$("[class^='form_']").change(function() {
var select = $(this);
var selectTime = $("#contact_time option:selected").val();
if (selectTime) {
select.removeClass("invalid").addClass("valid");
} else {
select.removeClass("valid").addClass("invalid");
}
});
/* Enquiry message*/
$("[class^='form_']").keyup(function(event) {
var input = $(this);
var enquiry = $(this).val();
if (enquiry) {
input.removeClass("invalid").addClass("valid");
} else {
input.removeClass("valid").addClass("invalid");
}
});
/* message*/
$("[class^='form_']").keyup(function(event) {
var input = $(this);
var message = $(this).val();
if (message) {
input.removeClass("invalid").addClass("valid");
} else {
input.removeClass("valid").addClass("invalid");
}
});
/* Submit */
$("[id^='submit_']").click(function(event) {
var form_data = $("[id^='form_']").serializeArray();
var error_free = true;
for (var input in form_data) {
var element = $("#contact_" + form_data[input]['name']);
var valid = element.hasClass("valid");
var error_element = $("span", element.parent());
if (!valid) {
error_element.removeClass("error").addClass("error_show");
error_free = false;
} else {
error_element.removeClass("error_show").addClass("error");
}
}
if (!error_free) {
return false;
} else {
$('.success_msg').fadeIn().delay(3000).fadeOut();
$('input , textarea , select').val('').removeClass('valid');
event.preventDefault();
}
});
});
.wrapper {
max-width: 1440px;
width: 100%;
margin: 0 auto;
position: relative;
}
.demos-nav {
position: relative;
display: flex;
flex-wrap: wrap;
margin: 40px auto;
justify-content: center;
align-items: center;
max-width: 1140px;
}
.success_msg {
width: 350px;
line-height: 40px;
border: 1px solid green;
border-radius: 5px;
background-color: rgba(213, 255, 187, 0.7);
display: none;
position: absolute;
bottom: 50px;
left: 50%;
transform: translateX(-50%);
z-index: 999;
text-align: center;
}
.iva-nav {
width: 100px;
text-align: center;
color: #fff;
font-size: 16px;
font-weight: 600;
transition: all 0.74s ease;
margin: 10px;
padding: 10px;
cursor: pointer;
position: relative;
transition: all .7s ease-in-out;
}
.iva-nav span {
transform: translateZ(8px);
user-select: none;
position: relative;
z-index: 999;
}
.iva-nav:before {
content: '';
position: absolute;
padding: 10px;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(254, 180, 29, 0.3);
box-sizing: border-box;
border: 1px solid rgba(255, 225, 225, 0.4);
transition: all 0.5s ease-in-out;
z-index: 50;
}
.iva-nav:after {
content: '';
position: absolute;
padding: 10px;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(254, 180, 29, 0.3);
box-sizing: border-box;
border: 1px solid rgba(255, 225, 225, 0.4);
transition: all 0.6s ease-in-out;
z-index: 25;
}
/*.iva-nav:hover {
transform: rotateX(-180deg) rotateY(180deg) rotateZ(180deg) ;
}*/
.iva-nav:hover:before {
transform: rotate(225deg);
background-color: rgba(254, 180, 29, 0.6);
border: 1px solid rgba(255, 225, 225, 0.1);
}
.iva-nav:hover:after {
transform: rotate(133deg);
background-color: rgba(254, 180, 29, 0.6);
border: 1px solid rgba(255, 225, 225, 0.1);
}
.fancy-heading-s1 {
max-width: 1400px;
width: 100%;
margin: 0 auto;
font-size: 40px;
padding: 25px 0;
color: #ffffff;
}
.fancy-heading-s2 {
font-size: 30px;
margin: 20px 0;
color: #fff;
}
.fancy-title {
display: block;
font-size: 13px;
margin: 20px 0;
font-weight: 400;
color: #ffffff;
}
.cfar-s1 .cfar-heading {
text-align: center;
}
*:focus {
outline: none;
}
.cfar {
max-width: 1140px;
width: 100%;
margin: 0 auto;
position: relative;
box-sizing: border-box;
}
.cfar-s1 {
padding: 40px 100px;
background-color: #313439;
}
.cfar-s1 .fancy-title span {
position: relative;
text-transform: uppercase;
cursor: pointer;
}
.cfar-s1 .fancy-title span:after {
content: " . ";
position: relative;
top: 50%;
display: inline-block;
transform: translateY(-15%);
margin: 0 10px;
}
.cfar-s1 .fancy-title span:last-child:after {
content: "";
margin-right: 0;
}
.cfar-s1 .fancy-heading-s2 h2 {
font-size: 40px;
font-weight: bold;
text-transform: uppercase;
}
.cfar-s1 .fancy-heading-s2 h2 span {
color: #da4e5b;
}
.cfar-s1 form {
padding: 30px 0;
display: flex;
flex-wrap: wrap;
justify-content: space-between;
}
.cfar .detail {
position: relative;
margin: 20px 0;
flex-basis: 48%;
}
.cfar .detail input,
.detail textarea,
.detail select {
display: block;
border: none;
border-bottom: 1px solid #fff;
padding: 5px 0;
width: 100%;
background: none;
color: #ffffff;
}
.cfar option {
background: rgba(0, 0, 0, 0.8);
}
.cfar .detail textarea {
height: 100px;
width: 100%;
overflow: auto;
resize: none;
}
.cfar .detail label {
position: absolute;
top: 0px;
left: 5px;
font-size: 16px;
pointer-events: none;
transition: all 0.43s ease-in-out;
}
.cfar .detail .inputBar {
position: relative;
display: block;
transition: all 0.43s ease-in-out;
}
.cfar .detail input:focus:after,
.detail textarea:foucs:after,
.detail select:focus:after,
.cfar .detail .inputBar:focus:before,
.cfar .detail .inputBar:focus:after {
content: "";
display: block;
position: absolute;
bottom: 0;
width: 0;
background: red;
height: 2px;
}
.cfar .detail .inputBar:after {
right: 50%;
}
.cfar .detail .inputBar:before {
left: 50%;
}
.cfar .detail input:focus~label,
.cfar .detail input:valid~label,
.cfar .detail textarea:focus~label,
.cfar .detail textarea:valid~label {
top: -20px;
transition: all 0.3s ease-in-out;
font-size: 13px;
}
.cfar .detail input:focus~.inputBar:before,
.cfar .detail input:focus~.inputBar:after,
.cfar .detail textarea:focus~.inputBar:before,
.cfar .detail textarea:focus~.inputBar:after .cfar .detail select:focus~.inputBar:before,
.cfar .detail select:focus~.inputBar:after {
width: 50%;
}
.cfar .detail .answer {
display: inline-block;
width: 114px;
height: 20px;
border: 1px solid #ffffff;
left: 133px;
position: inherit;
}
/* custom css*/
span.error {
/*display: none;*/
color: red;
opacity: 0;
position: absolute;
top: 10px !important;
right: 0;
transition: all 0.4s ease-in-out;
}
.error_show {
position: absolute;
top: 0;
right: 0;
color: red;
}
/*input.invalid,
textarea.invalid,
select.invalid {
border: 2px solid red;
}*/
input:focus {
outline-width: 0;
}
input[type=number]::-webkit-inner-spin-button,
input[type=number]::-webkit-outer-spin-button {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
margin: 0;
background-color: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
<div class="demos-nav">
<div class="iva-nav demo1" data-btn="demo1"><span>Demo 1</span></div>
<div class="iva-nav demo2" data-btn="demo2"><span>Demo 2</span></div>
</div>
<!-- demos nav -->
<div class="row current" id="demo1">
<div class="cfar cfar-s1">
<form id="form_info1" method="post" action="">
<div class="detail">
<input type="text" class="form_name1" id="contact_name1" name="name1" required autocomplete="off" />
<span class="inputBar"></span>
<!--inputBar-->
<label for="contact_name1">Name</label>
<span class="error">This field is required</span>
</div>
<!--detail-->
<div class="detail">
<input type="text" class="form_email1" id="contact_email1" name="email1" required autocomplete="off" />
<span class="inputBar"></span>
<!--inputBar-->
<label for="contact_email1">Email</label>
<span class="error">A valid email address is required</span>
</div>
<!--detail-->
<div class="detail">
<input type="number" class="form_phone1" id="contact_phone1" name="phone1" required autocomplete="off" />
<span class="inputBar"></span>
<!--inputBar-->
<label for="contact_phone1">Phone Number</label>
<span class="error">A valid Phone number is required</span>
</div>
<!--detail-->
<div class="detail">
<input type="text" class="form_enquiry1" id="contact_enquiry1" name="enquiry1" required autocomplete="off" />
<span class="inputBar"></span>
<!--inputBar-->
<label for="contact_enquiry">I want to know about...</label>
<span class="error">This field is required</span>
</div>
<!--detail-->
<div class="detail message">
<textarea type="text" class="form_message1" id="contact_message1" name="message1" required></textarea>
<span class="inputBar"></span>
<!--inputBar-->
<label for="contact_message1">Type your Message here</label>
<span class="error">This field is required</span>
</div>
<!--detail-->
<div class="btn-container" id="submit_form1">
<button type="submit" class="btn"> Submit</button>
</div>
</form>
<div class="success_msg">
<p>Form submitted Successfully</p>
</div>
</div>
<!-- Contact Form style 1 -->
</div>
<!-- row demo 1-->
<div class="row" id="demo2">
<div class="cfar cfar-s2">
<div class="cfar-form">
<h2 class="fancy-heading-s2"> Contact us </h2>
<span class="fancy-title"> Reach out to us for any Inquiry</span>
<form id="form_info2" method="post" action="">
<div class="detail">
<input type="text" class="form_name2" id="contact_name2" name="name2" required autocomplete="off" />
<span class="inputBar"></span>
<!--inputBar-->
<label for="contact_name2">Name</label>
<span class="error">This field is required</span>
</div>
<!--detail-->
<div class="detail">
<input type="text" class="form_email2" id="contact_email2" name="email2" required autocomplete="off" />
<span class="inputBar"></s1pan><!--inputBar-->
<label for="contact_email2">Email</label>
<span class="error">A valid email address is required</span>
</div>
<!--detail-->
<div class="detail">
<input type="number" class="form_phone2" id="contact_phone2" name="phone2" required autocomplete="off" />
<span class="inputBar"></span>
<!--inputBar-->
<label for="contact_phone2">Phone Number</label>
<span class="error">A valid Phone number is required</span>
</div>
<!--detail-->
<div class="detail message">
<textarea type="text" class="form_message2" id="contact_message2" name="message2" required></textarea>
<span class="inputBar"></span>
<!--inputBar-->
<label for="contact_message2">Type your Message here</label>
<span class="error">This field is required</span>
</div>
<!--detail-->
<div class="btn-container" id="submit_form2">
<button type="submit" class="btn"> Submit</button>
</div>
</form>
</div>
</div>
<!-- Contact Form style 2 -->
</div>
<!-- row demo 2-->
</div>
Do the following changes in your code and design.
In html, change button tag to input tag,
<div class="wrapper">
<div class="demos-nav">
<div class="iva-nav demo1" data-btn="demo1"><span>Demo 1</span></div>
<div class="iva-nav demo2" data-btn="demo2"><span>Demo 2</span></div>
</div>
<!-- demos nav -->
<div class="row current" id="demo1">
<div class="cfar cfar-s1">
<form id="form_info1" method="post" action="">
<div class="detail">
<input type="text" class="form_name1" id="contact_name1" name="name1" required autocomplete="off" />
<span class="inputBar"></span>
<!--inputBar-->
<label for="contact_name1">Name</label>
<span class="error">This field is required</span>
</div>
<!--detail-->
<div class="detail">
<input type="text" class="form_email1" id="contact_email1" name="email1" required autocomplete="off" />
<span class="inputBar"></span>
<!--inputBar-->
<label for="contact_email1">Email</label>
<span class="error">A valid email address is required</span>
</div>
<!--detail-->
<div class="detail">
<input type="text" class="form_phone1" id="contact_phone1" name="phone1" required autocomplete="off" />
<span class="inputBar"></span>
<!--inputBar-->
<label for="contact_phone1">Phone Number</label>
<span class="error">A valid Phone number is required</span>
</div>
<!--detail-->
<div class="detail">
<input type="text" class="form_enquiry1" id="contact_enquiry1" name="enquiry1" required autocomplete="off" />
<span class="inputBar"></span>
<!--inputBar-->
<label for="contact_enquiry">I want to know about...</label>
<span class="error">This field is required</span>
</div>
<!--detail-->
<div class="detail message">
<textarea type="text" class="form_message1" id="contact_message1" name="message1" required></textarea>
<span class="inputBar"></span>
<!--inputBar-->
<label for="contact_message1">Type your Message here</label>
<span class="error">This field is required</span>
</div>
<!--detail-->
<div class="btn-container" id="submit_form1">
<input type="button" class="btn" value="Submit"/>
</div>
</form>
<div class="success_msg">
<p>Form submitted Successfully</p>
</div>
</div>
<!-- Contact Form style 1 -->
</div>
<!-- row demo 1-->
<div class="row" id="demo2">
<div class="cfar cfar-s2">
<div class="cfar-form">
<h2 class="fancy-heading-s2"> Contact us </h2>
<span class="fancy-title"> Reach out to us for any Inquiry</span>
<form id="form_info2" method="post" action="">
<div class="detail">
<input type="text" class="form_name2" id="contact_name2" name="name2" required autocomplete="off" />
<span class="inputBar"></span>
<!--inputBar-->
<label for="contact_name2">Name</label>
<span class="error">This field is required</span>
</div>
<!--detail-->
<div class="detail">
<input type="text" class="form_email2" id="contact_email2" name="email2" required autocomplete="off" />
<span class="inputBar">
</s1pan><!--inputBar-->
<label for="contact_email2">Email</label>
<span class="error">A valid email address is required</span>
</div>
<!--detail-->
<div class="detail">
<input type="text" class="form_phone2" id="contact_phone2" name="phone2" required autocomplete="off" />
<span class="inputBar"></span>
<!--inputBar-->
<label for="contact_phone2">Phone Number</label>
<span class="error">A valid Phone number is required</span>
</div>
<!--detail-->
<div class="detail message">
<textarea type="text" class="form_message2" id="contact_message2" name="message2" required></textarea>
<span class="inputBar"></span>
<!--inputBar-->
<label for="contact_message2">Type your Message here</label>
<span class="error">This field is required</span>
</div>
<!--detail-->
<div class="btn-container" id="submit_form2">
<input type="button" class="btn" value="Submit"/>
</div>
</form>
</div>
</div>
<!-- Contact Form style 2 -->
</div>
<!-- row demo 2-->
</div>
The script is,
$(document).ready(function () {
/* contact form tabs*/
function button() {
$('.demos-nav .iva-nav').click(function () {
var btn = $(this).data('btn');
$('.row').removeClass('current').css('display', 'none');
$('.demos-nav .iva-nav').removeClass('current');
$(this).addClass('current');
$("#" + btn).addClass('current').css('display', 'block');
})
}
button();
/* name*/
$("[class^='form_name']").on('change', function () {
var input = $(this);
var is_name = input.val();
if (is_name) {
$(input).removeClass("invalid");
$(input).addClass("valid");
} else {
$(input).removeClass("valid");
$(input).addClass("invalid");
}
});
/* E-mail */
$("[class^='form_email']").on('change', function () {
var input = $(this);
var regex = /^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/;
var is_email = regex.test(input.val());
if (is_email) {
input.removeClass("invalid").addClass("valid");
} else {
input.removeClass("valid").addClass("invalid");
}
});
/* Phone */
$("[class^='form_phone']").on('change', function () {
var input = $(this);
var regex = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
var is_phone = regex.test(input.val());
if (is_phone) {
input.removeClass("invalid").addClass("valid");
} else {
input.removeClass("valid").addClass("invalid");
}
});
/* Enquiry message*/
$("[class^='form_enquiry']").keyup(function (event) {
var input = $(this);
var enquiry = $(this).val();
if (enquiry) {
input.removeClass("invalid").addClass("valid");
} else {
input.removeClass("valid").addClass("invalid");
}
});
/* message*/
$("[class^='form_message']").keyup(function (event) {
var input = $(this);
var message = $(this).val();
if (message) {
input.removeClass("invalid").addClass("valid");
} else {
input.removeClass("valid").addClass("invalid");
}
});
/* Submit */
$("[id^='submit_']").click(function (event) {
var form_data = $(this).parent().serializeArray();
var error_free = true;
for (var input in form_data) {
var element = $("#contact_" + form_data[input]['name']);
var valid = element.hasClass("valid");
var error_element = $("span", element.parent());
if (!valid) {
error_element.removeClass("error").addClass("error_show");
error_free = false;
} else {
error_element.removeClass("error_show").addClass("error");
}
}
if (!error_free) {
return false;
} else {
$('.success_msg').fadeIn().delay(3000).fadeOut();
$('input , textarea , select').val('').removeClass('valid');
event.preventDefault();
}
});
});
In the submit handler, you are referencing both the forms. which is why validations in both the forms are firing. Try getting the reference of the form to which the clicked submit button belongs to.
$("[id^='submit_']").click(function(event) {
var form = $(this).closest("form");
var form_data = form.serializeArray();
//remaining code
Hope this gives you an idea.
Did you try to use newest version of jQuery?? Like: 3.3.1
updated
Try to change all your if statements for example:
/* name*/
$("[class^='form_']").on('input', function() {
var input = $(this);
var is_name = input.val();
if (is_name === ' ') {
input.removeClass("valid").addClass("invalid");
} else {
input.removeClass("invalid").addClass("valid");
}
});
codepen
Related
In the snippet below, I have a step-form. While submitting the content in the form and hitting next, the input values are being passed to the confirmation page at the end.
I'm trying to understand if this is the most efficient way to pass the information to the confirmation page?
const previousButton = document.getElementById("previous")
const nextButton = document.getElementById("next")
const submitButton = document.getElementById('validate')
const form = document.getElementById('stepByStepForm')
const dots = document.getElementsByClassName('progress-bar__dot')
const numberOfSteps = 5
let currentStep = 1
for(let i = 0 ; i < dots.length ; ++i){
dots[i].addEventListener('click', ()=>{
goToStep(i+1)
})
}
previousButton.onclick = goPrevious
nextButton.onclick = goNext
function goNext(e) {
e.preventDefault()
currentStep += 1
goToStep(currentStep)
}
function goPrevious(e) {
e.preventDefault()
currentStep -= 1
goToStep(currentStep)
}
function goToStep(stepNumber){
currentStep = stepNumber
let inputsToHide = document.getElementsByClassName('step')
let inputs = document.getElementsByClassName(`step${currentStep}`)
let indicators = document.getElementsByClassName('progress-bar__dot')
for(let i = indicators.length-1; i >= currentStep ; --i){
indicators[i].classList.remove('full')
}
for(let i = 0; i < currentStep; ++i){
indicators[i].classList.add('full')
}
//hide all input
for (let i = 0; i < inputsToHide.length; ++i) {
hide(inputsToHide[i])
}
//only show the right one
for (let i = 0; i < inputs.length; ++i) {
show(inputs[i])
}
//if we reached final step
if(currentStep === numberOfSteps){
enable(previousButton)
disable(nextButton)
show(submitButton)
}
//else if first step
else if(currentStep === 1){
disable(previousButton)
enable(next)
hide(submitButton)
}
else {
enable(previousButton)
enable(next)
hide(submitButton)
}
}
function enable(elem) {
elem.classList.remove("disabled");
elem.disabled = false;
}
function disable(elem) {
elem.classList.add("disabled");
elem.disabled = true;
}
function show(elem){
elem.classList.remove('hidden')
}
function hide(elem){
elem.classList.add('hidden')
}
//collect inputs
next.addEventListener('click', function() {
const fNameInput = document.getElementById('firstname').value;
document.getElementById('fNameOutput').textContent = fNameInput;
const lNameInput = document.getElementById('lastname').value;
document.getElementById('lNameOutput').textContent = lNameInput;
const emailInput = document.getElementById('mail').value;
document.getElementById('emailOutput').textContent = emailInput;
const phoneInput = document.getElementById('phone').value;
document.getElementById('phoneOutput').textContent = phoneInput;
const addressInput = document.getElementById('address').value;
document.getElementById('addressOutput').textContent = addressInput;
const countryInput = document.getElementById('country').value;
document.getElementById('countryOutput').textContent = countryInput;
const colorInput = document.getElementById('color').value;
document.getElementById('colorOutput').textContent = colorInput;
const animalInput = document.getElementById('animal').value;
document.getElementById('animalOutput').textContent = animalInput;
});
submitButton.addEventListener('click', function(e) {
e.preventDefault();
})
html {
background-color: #A2C7E5;
}
.hidden {
display: none;
}
.button {
width: 140px;
cursor: pointer;
padding: 1em;
border-radius: 0.2em;
border: none;
color: white;
font-weight: bold;
font-size: 1em;
transition: all 0.5s ease;
background-color: #ff8552;
}
.button:hover {
background-color: #ff4f06;
}
.button.disabled {
opacity: 0.5;
}
.button.disabled:hover {
background-color: #ff8552;
}
.form {
width: 20em;
margin: auto;
margin-top: 5em;
padding: 5em;
padding-top: 2em;
padding-bottom: 2em;
background-color: white;
font-family: "Raleway", sans-serif;
color: #33312E;
border-radius: 0.2em;
box-shadow: 0 10px 20px rgba(0, 0, 0, 0.19), 0 6px 6px rgba(0, 0, 0, 0.23);
}
.form .progress-bar {
width: 100%;
list-style-type: none;
display: flex;
padding: 0;
justify-content: center;
margin-bottom: 3.5em;
}
.form .progress-bar li.progress-bar__dot {
display: block;
width: 0.6em;
border-radius: 50%;
height: 0.6em;
border: 0.1em solid #ff8552;
background-color: white;
cursor: pointer;
transition: all 0.5s ease;
}
.form .progress-bar li.progress-bar__dot.full {
background-color: #ff8552;
}
.form .progress-bar li.progress-bar__connector {
display: block;
width: 5em;
border-radius: 1000em;
height: 0.1em;
background-color: #ff8552;
margin-top: 0.35em;
}
.form label {
font-weight: bold;
font-size: 1.2em;
}
.form input {
width: 100%;
padding: 1.3em;
margin-bottom: 3em;
box-sizing: border-box;
margin-top: 1em;
border: none;
border-radius: 0.5em;
background-color: #e6e6e6;
font-size: 1em;
font-family: "Raleway", sans-serif;
}
.form input:focus {
border: none;
}
.form .button-group {
width: 100%;
display: flex;
justify-content: space-between;
margin-top: 50px;
}
.form button#validate {
margin: auto;
background-color: #1A936F;
width: 12em;
}
.form button#validate:hover {
background-color: #12684e;
}
<form id="stepByStepForm" class="form">
<ul class="progress-bar">
<li class="progress-bar__dot full"></li>
<li class="progress-bar__connector"></li>
<li class="progress-bar__dot"></li>
<li class="progress-bar__connector"></li>
<li class="progress-bar__dot"></li>
<li class="progress-bar__connector"></li>
<li class="progress-bar__dot"></li>
<li class="progress-bar__connector"></li>
<li class="progress-bar__dot"></li>
</ul>
<div class="step step1">
<div class="input-group">
<label for="firstname">First name</label>
<input type="text" value="James" name="firstname" id="firstname">
</div>
<div class="input-group">
<label for="lastname">Last name</label>
<input type="text" value="Smith" name="lastname" id="lastname">
</div>
</div>
<div class="step step2 hidden">
<div class="input-group">
<label for="mail">E-mail</label>
<input type="mail" value="jamessmith#gmail.com" name="mail" id="mail">
</div>
<div class="input-group">
<label for="phone">Phone</label>
<input type="text" value="602-379-1395" name="phone" id="phone">
</div>
</div>
<div class="step step3 hidden">
<div class="input-group">
<label for="address">Address</label>
<input type="text" value="221B Baker Street" name="address" id="address">
</div>
<div class="input-group">
<label for="country">Country</label>
<input type="text" value="United States" name="country" id="country">
</div>
</div>
<div class="step step4 hidden">
<div class="input-group">
<label for="color">Favorite Color</label>
<input type="text" value="Blue" name="color" id="color">
</div>
<div class="input-group">
<label for="animal">Favorite Animal</label>
<input type="text" value="Lion" name="animal" id="animal">
</div>
</div>
<div class="step step5 hidden">
<h4>Name:</h4>
<p><strong>First Name:</strong> <span id="fNameOutput"></span></p>
<p><strong>Last Name:</strong> <span id="lNameOutput"></span></p>
<hr>
<h4>Contact:</h4>
<p><strong>Email:</strong> <span id="emailOutput"></span></p>
<p><strong>Phone:</strong> <span id="phoneOutput"></span></p>
<hr>
<h4>Location:</h4>
<p><strong>Address:</strong> <span id="addressOutput"></span></p>
<p><strong>Country:</strong> <span id="countryOutput"></span></p>
<hr>
<h4>Attributes:</h4>
<p><strong>Favorite Color:</strong> <span id="colorOutput"></span></p>
<p><strong>Favorite Animal:</strong> <span id="animalOutput"></span></p>
</div>
<div class="button-group">
<button id="previous" class="disabled button" disabled>
previous
</button>
<button id="next" class="button">
next
</button>
</div>
<div class="button-group">
<button id="validate" type="submit" class="hidden button">
Submit
</button>
</div>
</form>
There are 3 problems:
In this part next.addEventListener('click', function() {...}, it updates all texts every time the next button is pressed.
document.getElementById(ID_NAME).textContent = VALUE; is written repeatedly; It is not that bad but there are more readable ways.
The confirmation textContents are not updated when the last dot is clicked.
First, make a function to update texts. To avoid writing similar code repeatedly, you can use an Object for ids and for...of to implement updating the text contents.
function updateConfirmText() {
const map = {
firstname: 'fNameOutput',
lastname: 'lNameOutput',
mail: 'emailOutput',
phone: 'phoneOutput',
address: 'addressOutput',
country: 'countryOutput',
color: 'colorOutput',
animal: 'animalOutput'
};
for (const [input, output] of Object.entries(map)) {
document.getElementById(output).textContent = document.getElementById(input).value;
}
}
Second, call the function in the if statement that you have already written.
//if we reached final step
if (currentStep === numberOfSteps) {
enable(previousButton)
disable(nextButton)
show(submitButton)
updateConfirmText(); // Add
}
I hope it works🤞
I want to validate a multipage form using Js. Here is what I want the code to be, when I click 'next' i want it to validate whether the radio button has been checked or not. If not then display an alert popup. The multipage form already works but the problem here is I cannot validate the radio button on each page.
Hope anyone can help me solve this problem since I have been few days trying to solve this problem but I don't know how to do it. Thank you in advance.
HTML
<form class="form" action="" method="post">
<!-- Progress bar -->
<div class="progressbar">
<div class="progress" id="progress"></div>
<div class="progress-step progress-step-active" data-title="DEPARTMENT"></div>
<div class="progress-step" data-title="BLOCK"></div>
<div class="progress-step" data-title="TITLE"></div>
<div class="progress-step" data-title="DESCRIPTION"></div>
<div class="progress-step" data-title="DONE"></div>
</div>
<!-- start Steps 1-->
<div class="form-step form-step-active">
<br/>
<div class="page-header">
<h1>First, choose one department that is related to the complaint you are about to make.
<span style="color:#ffef96; font-size:15px;"><br/>
<p>Click any department for hint</p>
</span>
</h1>
<br/>
<div class="radio-toolbar">
<input type="radio" id="radio1" name="cdepartment" class="hint" value="GENERAL" required/>
<label for="radio1">GENERAL
<span class="hintclick"> e-Aduan UiTM used for
<span style="color:#ffef96">general complaints about UiTM.</span>
</span>
</label>
<input type="radio" id="radio2" name="cdepartment" class="hint" value="FACILITIES"/>
<label for="radio2">FACILITIES
<span class="hintclick">For
<span style="color:#ffef96">electrical, mechanical, telecommunications, event management.</span>
</span>
</label>
<input type="radio" id="radio3" name="cdepartment" class="hint" value="ICT"/>
<label for="radio3">ICT
<span class="hintclick">e-Aduan ICT used for
<span style="color:#ffef96">ICT complaints </span>
</label>
</div>
<br/>
</div><!-- page header-->
<div class="width-50 ml-auto" >
NEXT
</div>
</div>
<!-- end Steps 1 -->
<!-- start Steps 2 -->
<div class="form-step">
<br/>
<div class="page-header">
<h1>Second, which block do you wish to complaint about?</h1>
<br/>
<div class="radio-toolbar">
<div class="grid-container">
<?php
$count=4;
$sql="SELECT * FROM `block`";
$result=mysqli_query($connection,$sql);
while($std=mysqli_fetch_array($result))
{
?>
<input type="radio" id="<?php echo $std['bid'];?>" name="cblock" value="<?php echo $std['blockname'];?>" required/>
<label for="<?php echo $std['bid'];?>"><?php echo $std['blockname'];?></label>
<br/>
<?php }?>
</div>
</div>
</div> <!-- page header-->
<div class="btns-group width-50 ml-auto">
PREVIOUS
NEXT
</div>
</div>
<!-- end Steps 2 -->
<!-- start Steps 3 -->
<div class="form-step">
<br/>
<div class="page-header">
<h1>Third, pick a title or topic
<span style="color:#ffef96; font-size:15px;"><br/>
<p>If your related toppic is not listed, please fill in below text box instead.</p>
</span>
</h1>
<br/>
<div class="radio-toolbar">
<input type="radio" id="radioApple" name="radioFruit" value="apple" required/>
<label for="radioApple">Apple</label>
<input type="radio" id="radioBanana" name="radioFruit" value="banana"/>
<label for="radioBanana">Banana</label>
<input type="radio" id="radioOrange" name="radioFruit" value="orange"/>
<label for="radioOrange">Orange</label>
</div>
<div class="input-group">
<textarea type="text" class="form-control" row="5" name="cdescription" placeholder="Write here.." required/></textarea>
</div>
<br/>
</div>
<div class="btns-group width-50 ml-auto">
PREVIOUS
NEXT
</div>
</div>
<!-- end Steps 3 -->
<!-- start Steps 4 -->
<div class="form-step">
<div class="page-header">
<h1>Lastly, state your description regarding the complaint made
<span style="color:#ffef96; font-size:15px;"><br/>
<p> Below box you can write any notes about the complaint so the staff can help to understand</p>
</span>
</h1>
<br/>
<div class="input-group">
<textarea type="text" class="form-control" row="5" name="cdescription" placeholder="Write here.." required/></textarea>
</div>
</div>
<div class="btns-group width-50 ml-auto">
PREVIOUS
<button class="btn" type="submit" name="submit">SUBMIT</button>
</div>
</div>
<!-- end Steps 4 -->
<!-- start Steps 5 -->
<div class="form-step">
<div class="page-header">
<h1>THANK YOU <br/>
YOU CAN SEE RECENT COMPLAINT ON YOUR HOMEPAGE
</h1>
</div>
<!-- end Steps 5 -->
</form>
CSS
:root {
--primary-color: rgb(165, 121, 64);
}
*,
*::before,
*::after {
box-sizing: border-box;
}
.width-50 {
width: 30%;
}
.ml-auto {
margin-left: auto;
}
/* Progressbar */
.progressbar {
position: relative;
display: flex;
justify-content: space-between;
counter-reset: step;
margin: 2rem 4rem;
}
.progressbar::before,
.progress {
content: "";
position: absolute;
top: 50%;
transform: translateY(-50%);
height: 4px;
width: 100%;
background-color: #dcdcdc;
z-index: -1;
}
.progress {
background-color: var(--primary-color);
width: 0%;
transition: 0.3s;
}
.progress-step {
width: 2.1875rem;
height: 2.1875rem;
background-color: #dcdcdc;
border-radius: 50%;
display: flex;
justify-content: center;
align-items: center;
}
.progress-step::before {
counter-increment: step;
content: counter(step);
}
.progress-step::after {
content: attr(data-title);
position: absolute;
top: calc(100% + 0.5rem);
font-size: 0.85rem;
color: #666;
}
.progress-step-active {
background-color: var(--primary-color);
color: #f3f3f3;
}
/* Form */
.form {
width: 80%;
margin: 30px auto;
border: 1px solid #ccc;
border-radius: 0.35rem;
padding: 1.5rem;
box-shadow:
4px 4px 4px 0px #d1d9e6 inset,
-4px -4px 4px 0px #ffffff inset;
}
.form-step {
display: none;
transform-origin: top;
animation: animate 0.5s;
}
.form-step-active {
display: block;
}
.input-group {
margin: 2rem 0;
}
#keyframes animate {
from {
transform: scale(1, 0);
opacity: 0;
}
to {
transform: scale(1, 1);
opacity: 1;
}
}
.row{
height:100%;
width: 50px;
}
/* Button */
.btns-group {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 1.5rem;
}
.btn {
padding: 16px;
display: block;
text-decoration: none;
background-color: rgba(0, 0, 0, 0.2);
color: #f3f3f3;
text-align: center;
border-radius: 0.25rem;
cursor: pointer;
transition: 0.3s;
border-radius: 15px 25px;
box-shadow: 5px 8px 10px #888888;
}
.btn:hover {
box-shadow: 0 0 0 2px #fff, 0 0 0 3px ;
color: #f3f3f3;
}
/* end progress bar*/
.radio-toolbar {
margin-left: 10px;
text-align: center;
}
.radio-toolbar input[type="radio"] {
opacity: 0;
position: fixed;
width: 0;
}
.radio-toolbar label {
display: inline-block;
background-color: #f0efef;
padding: 10px;
font-size: 18px;
border: 3px solid #444;
border-radius: 4px;
width: 300px;
height:auto;
}
.radio-toolbar label:hover {
background-color: #c2d4dd;
cursor: pointer;
}
.radio-toolbar input[type="radio"]:focus + label {
border: 2px dashed #f0efef;
}
.radio-toolbar input[type="radio"]:checked + label {
background-color:#a57940;
border-color: #c2d4dd;
}
/* end radio button*/
.hint, label .hintclick {
display: none;
opacity: 0;
}
.hint:checked+ label .hintclick {
display: block;
opacity: 1;
font-size: 17px;
color: white;
}
.grid-container {
display: grid;
grid-template-columns: auto auto auto auto auto auto auto auto ;
}
.grid-container > label {
width: 100%;
}
JS
const prevBtns = document.querySelectorAll(".btn-prev");
const nextBtns = document.querySelectorAll(".btn-next");
const progress = document.getElementById("progress");
const formSteps = document.querySelectorAll(".form-step");
const progressSteps = document.querySelectorAll(".progress-step");
let formStepsNum = 0;
nextBtns.forEach((btn) => {
btn.addEventListener("click", () => {
formStepsNum++;
updateFormSteps();
updateProgressbar();
});
});
prevBtns.forEach((btn) => {
btn.addEventListener("click", () => {
formStepsNum--;
updateFormSteps();
updateProgressbar();
});
});
function updateFormSteps() {
formSteps.forEach((formStep) => {
formStep.classList.contains("form-step-active") &&
formStep.classList.remove("form-step-active");
});
formSteps[formStepsNum].classList.add("form-step-active");
}
function updateProgressbar() {
progressSteps.forEach((progressStep, idx) => {
if (idx < formStepsNum + 1) {
progressStep.classList.add("progress-step-active");
} else {
progressStep.classList.remove("progress-step-active");
}
});
const progressActive = document.querySelectorAll(".progress-step-active");
progress.style.width =
((progressActive.length - 1) / (progressSteps.length - 1)) * 100 + "%";
}
This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Uncaught TypeError: Cannot read property 'value' of null [duplicate]
(10 answers)
Closed last month.
I am trying to validate a contact form but none of my JavaScript is working but I guess my event listener is the problem because my page still refreshes on click of the button. It returned an error in the console
Uncaught TypeError: Cannot read property 'addEventListener' of null
const form = document.getElementById('form');
const client = document.getElementById('name');
const email = document.getElementById('email');
const message = document.getElementById('text-message');
// Show input error message
function showError(input, message) {
const formControl = input.parentElement;
formControl.className = 'form-control error';
const small = formControl.querySelector('small');
small.innerText = message;
}
// Show success outline
function showSuccess(input) {
const formControl = input.parentElement;
formControl.className = 'form-control success';
}
// Check email is valid
function checkEmail(input) {
const re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (re.test(input.value.trim())) {
showSuccess(input);
} else {
showError(input, 'Email is not valid');
}
}
// Check required fields
function checkRequired(inputArr) {
inputArr.forEach(function(input) {
if (input.value.trim() === '') {
showError(input, `${getFieldName(input)} is required`);
} else {
showSuccess(input);
}
});
}
// Get fieldname
function getFieldName(input) {
return input.id.charAt(0).toUpperCase() + input.id.slice(1);
}
// Event listeners
form.addEventListener('submit', function(e) {
e.preventDefault();
checkRequired([client, email, message]);
checkEmail(email);
});
.container {
display: flex;
justify-content: flex-start;
flex-direction: column;
width: 30rem;
padding: 0rem 10rem; }
.container .submit-btn {
margin-top: 4rem; }
.container input {
width: 20rem;
height: 2rem;
background-color: var(--color-blue);
border: 1px solid #0652b9;
border-color: #0652b9;
border-radius: 2.5rem;
display: block;
color: #161616;
text-indent: 15px; }
.container input:focus {
outline: 0;
border-color: #ff8b2c; }
.container textarea {
width: 20rem;
height: 10rem;
background-color: var(--color-blue);
border: 1px solid #0652b9;
border-color: #0652b9;
border-radius: 1.5rem;
color: #161616;
text-indent: 15px; }
.container textarea:focus {
outline: 0;
border-color: #ff8b2c; }
.container ::placeholder {
color: #161616;
opacity: 0.5; }
.container .form-control {
position: relative; }
.container .form-control.success input {
border-color: green; }
.container .form-control.error input {
border-color: red; }
.container .form-control small {
color: red;
bottom: 0;
left: 0;
visibility: hidden; }
.container .form-control.error small {
visibility: visible; }
button {
width: 7rem;
height: 3rem;
background: #0652b9;
border-style: none;
border-radius: 2.5rem;
color: #ffffff; }
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="../css/main.css" />
</head>
<body>
<section class="container">
<form action="/" method="GET" id="form" class="form">
<div class="form-control">
<!-- <label for="name">Name</label> -->
<input type="text" id="client" placeholder="Your name">
<small>Error message</small>
</div>
<div class="form-control">
<!-- <label for="email">Email</label> -->
<input type="text" id="email" placeholder="Your email">
<small>Error message</small>
</div>
<div class="form-control">
<!-- <label for="message">Message</label> -->
<textarea name="message" id="text-message" rows="7" placeholder="Say something about your project"></textarea>
<small>Error message</small>
</div>
<button class="submit-btn" type="submit">Send message</button>
</form>
</section>
<script src="validation.js"></script>
</body>
</html>
Your selector for the variable client should be client instead of name
const form = document.getElementById('form');
const client = document.getElementById('client');
const email = document.getElementById('email');
const message = document.getElementById('text-message');
// Show input error message
function showError(input, message) {
const formControl = input.parentElement;
formControl.className = 'form-control error';
const small = formControl.querySelector('small');
small.innerText = message;
}
// Show success outline
function showSuccess(input) {
const formControl = input.parentElement;
formControl.className = 'form-control success';
}
// Check email is valid
function checkEmail(input) {
const re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (re.test(input.value.trim())) {
showSuccess(input);
} else {
showError(input, 'Email is not valid');
}
}
// Check required fields
function checkRequired(inputArr) {
inputArr.forEach(function(input) {
if (input.value.trim() === '') {
showError(input, `${getFieldName(input)} is required`);
} else {
showSuccess(input);
}
});
}
// Get fieldname
function getFieldName(input) {
return input.id.charAt(0).toUpperCase() + input.id.slice(1);
}
// Event listeners
form.addEventListener('submit', function(e) {
e.preventDefault();
checkRequired([client, email, message]);
checkEmail(email);
});
.container {
display: flex;
justify-content: flex-start;
flex-direction: column;
width: 30rem;
padding: 0rem 10rem; }
.container .submit-btn {
margin-top: 4rem; }
.container input {
width: 20rem;
height: 2rem;
background-color: var(--color-blue);
border: 1px solid #0652b9;
border-color: #0652b9;
border-radius: 2.5rem;
display: block;
color: #161616;
text-indent: 15px; }
.container input:focus {
outline: 0;
border-color: #ff8b2c; }
.container textarea {
width: 20rem;
height: 10rem;
background-color: var(--color-blue);
border: 1px solid #0652b9;
border-color: #0652b9;
border-radius: 1.5rem;
color: #161616;
text-indent: 15px; }
.container textarea:focus {
outline: 0;
border-color: #ff8b2c; }
.container ::placeholder {
color: #161616;
opacity: 0.5; }
.container .form-control {
position: relative; }
.container .form-control.success input {
border-color: green; }
.container .form-control.error input {
border-color: red; }
.container .form-control small {
color: red;
bottom: 0;
left: 0;
visibility: hidden; }
.container .form-control.error small {
visibility: visible; }
button {
width: 7rem;
height: 3rem;
background: #0652b9;
border-style: none;
border-radius: 2.5rem;
color: #ffffff; }
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="../css/main.css" />
</head>
<body>
<section class="container">
<form action="/" method="GET" id="form" class="form">
<div class="form-control">
<!-- <label for="name">Name</label> -->
<input type="text" id="client" placeholder="Your name">
<small>Error message</small>
</div>
<div class="form-control">
<!-- <label for="email">Email</label> -->
<input type="text" id="email" placeholder="Your email">
<small>Error message</small>
</div>
<div class="form-control">
<!-- <label for="message">Message</label> -->
<textarea name="message" id="text-message" rows="7" placeholder="Say something about your project"></textarea>
<small>Error message</small>
</div>
<button class="submit-btn" type="submit">Send message</button>
</form>
</section>
<script src="validation.js"></script>
</body>
</html>
It gets submitted duo to an error is in there. Just change:
const client = document.getElementById('name');
to
const client = document.getElementById('client');
How to Validate? Don’t allow Gmail, Yahoo, etc email addresses. And one more issue is that when all the fields are not entered submit should be disabled. when i fill all submit is enabled and when i remove one input after filling it, submit should be disabled, but still it's enabled. How to fix that?
$("#passwordv").on("focusout", function (e) {
if ($(this).val() != $("#passwordvConfirm").val()) {
$("#passwordvConfirm").removeClass("valid").addClass("invalid");
$('#btn-1').show();
} else {
$("#passwordvConfirm").removeClass("invalid").addClass("valid");
$('#btn').removeAttr("disabled");
$('#btn-1').hide();
}
});
$("#passwordvConfirm").on("keyup", function (e) {
if ($("#passwordv").val() != $(this).val()) {
$(this).removeClass("valid").addClass("invalid");
$('#btn-1').show();
} else {
$(this).removeClass("invalid").addClass("valid");
$('#btn').removeAttr("disabled");
$('#btn-1').hide();
}
});
$(document).ready(function () {
$('#passwordv').keyup(function () {
$('#result').html(checkStrength($('#passwordv').val()))
})
function checkStrength(password) {
var strength = 0
if (password.length < 6) {
$('#result').removeClass()
$('#result').addClass('short')
return 'Too short'
}
if (password.length > 7) strength += 1
// If password contains both lower and uppercase characters, increase strength value.
if (password.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/)) strength += 1
// If it has numbers and characters, increase strength value.
if (password.match(/([a-zA-Z])/) && password.match(/([0-9])/)) strength += 1
// If it has one special character, increase strength value.
if (password.match(/([!,%,&,#,#,$,^,*,?,_,~])/)) strength += 1
// If it has two special characters, increase strength value.
if (password.match(/(.*[!,%,&,#,#,$,^,*,?,_,~].*[!,%,&,#,#,$,^,*,?,_,~])/)) strength += 1
// Calculated strength value, we can return messages
// If value is less than 2
if (strength < 2) {
$('#result').removeClass()
$('#result').addClass('weak')
return 'Weak'
} else if (strength == 2) {
$('#result').removeClass()
$('#result').addClass('good')
return 'Good'
} else {
$('#result').removeClass()
$('#result').addClass('strong')
return 'Strong'
}
}
});
$('.form').find('input, textarea').on('keyup blur focus', function (e) {
var $this = $(this),
label = $this.prev('label');
if (e.type === 'keyup') {
if ($this.val() === '') {
label.removeClass('active highlight');
} else {
label.addClass('active highlight');
}
} else if (e.type === 'blur') {
if ($this.val() === '') {
label.removeClass('active highlight');
} else {
label.removeClass('highlight');
}
} else if (e.type === 'focus') {
if ($this.val() === '') {
label.removeClass('highlight');
} else if ($this.val() !== '') {
label.addClass('highlight');
}
}
});
$('.tab a').on('click', function (e) {
e.preventDefault();
$(this).parent().addClass('active');
$(this).parent().siblings().removeClass('active');
target = $(this).attr('href');
$('.tab-content > div').not(target).hide();
$(target).fadeIn(600);
});
*,
*:before,
*:after {
box-sizing: border-box;
}
html {
overflow-y: scroll;
}
body {
background: #f1f0ee;
font-family: 'Titillium Web', sans-serif;
}
a {
text-decoration: none;
color: #1ab188;
transition: .5s ease;
}
a:hover {
color: #179b77;
}
.form {
background: rgba(19, 35, 47, 0.9);
padding: 40px;
max-width: 600px;
margin: 130px auto;
border-radius: 4px;
box-shadow: 0 4px 10px 4px rgba(19, 35, 47, 0.3);
}
#media only screen and (max-width: 768px) {
.form {
background: rgba(19, 35, 47, 0.9);
padding: 40px;
max-width: 600px;
margin: 30px auto;
border-radius: 4px;
box-shadow: 0 4px 10px 4px rgba(19, 35, 47, 0.3);
}
}
.tab-group {
list-style: none;
padding: 0;
margin: 0 0 40px 0;
}
.tab-group:after {
content: "";
display: table;
clear: both;
}
.tab-group li a {
display: block;
text-decoration: none;
padding: 15px;
background: rgba(160, 179, 176, 0.25);
color: #a0b3b0;
font-size: 20px;
float: left;
width: 50%;
text-align: center;
cursor: pointer;
transition: .5s ease;
}
.tab-group li a:hover {
background: #179b77;
color: #ffffff;
}
.tab-group .active a {
background: #1ab188;
color: #ffffff;
}
.tab-content>div:last-child {
display: none;
}
h1 {
text-align: center;
color: #ffffff !important;
font-weight: 300;
margin: 0 0 40px !important;
}
label {
position: absolute;
-webkit-transform: translateY(6px);
transform: translateY(6px);
left: 13px;
color: rgba(255, 255, 255, 0.5);
transition: all 0.25s ease;
-webkit-backface-visibility: hidden;
pointer-events: none;
margin-top: 18px;
}
label .req {
margin: 2px;
color: #1ab188;
}
label.active {
-webkit-transform: translateY(-25px);
transform: translateY(-25px);
left: 2px;
font-size: 14px;
}
label.active .req {
opacity: 0;
}
label.highlight {
color: #ffffff;
}
input,
textarea {
font-size: 22px;
display: block;
width: 100%;
height: 100%;
padding: 8px 10px;
background: none;
background-image: none;
border: 1px solid #a0b3b0;
color: #ffffff;
border-radius: 0;
transition: border-color .25s ease, box-shadow .25s ease;
}
input:focus,
textarea:focus {
outline: 0;
border-color: #1ab188;
}
textarea {
border: 2px solid #a0b3b0;
resize: vertical;
}
.field-wrap {
position: relative;
margin-bottom: 25px;
}
.top-row:after {
content: "";
display: table;
clear: both;
}
.top-row>div {
float: left;
width: 48%;
margin-right: 4%;
}
.top-row>div:last-child {
margin: 0;
}
.button {
border: 0;
outline: none;
border-radius: 50px;
padding: 15px 0;
font-size: 20px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: .1em;
background: #1ab188;
color: #ffffff;
transition: all 0.5s ease;
-webkit-appearance: none;
}
.button:hover,
.button:focus {
background: #179b77;
}
.button-block {
display: block;
width: 50%;
margin: 0 auto;
}
.forgot {
text-align: right;
}
#toast-container {
top: 4% !important;
right: 40% !important;
left: 40%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Compiled and minified CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<!-- Compiled and minified JavaScript -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<div class="form">
<ul class="tab-group">
<li class="tab active">Log In</li>
<li class="tab">Sign Up</li>
</ul>
<div class="tab-content">
<div id="login">
<form id="form_id" method="post" name="myform">
<div class="field-wrap">
<label>
User Name<span class="req">*</span>
</label>
<input type="text" autocomplete="off" name="username" id="username" required>
</div>
<div class="field-wrap">
<label>
Password<span class="req">*</span>
</label>
<input type="password" autocomplete="off" name="password" id="password" required>
</div>
<p class="forgot">Forgot Password?</p>
<input type="button" value="Log in" id="submit" onclick="validate()" class="button button-block">
</form>
</div>
<div id="signup">
<form>
<div class="field-wrap">
<label>
Name<span class="req">*</span>
</label>
<input type="text" required autocomplete="off" />
</div>
<div class="field-wrap">
<label>
Email Address<span class="req">*</span>
</label>
<input type="email" required autocomplete="off" />
</div>
<div class="field-wrap">
<label>
Company Details<span class="req">*</span>
</label>
<input type="text" required autocomplete="off" />
</div>
<div class="field-wrap">
<label for="passwordv">
Set A Password<span class="req">*</span>
</label>
<input id="passwordv" type="password" class="validate" required autocomplete="off" />
<span id="result" style="color: white;"></span>
</div>
<div class="field-wrap" style="margin-bottom: 0px">
<label id="lblPasswordvConfirm" for="passwordvConfirm" data-error="Password not match"
data-success="Password Match">
Confirm Password<span class="req">*</span>
</label>
<input id="passwordvConfirm" type="password" required autocomplete="off" />
</div>
<label class="field-wrap" id="btn-1" style="display: none;color: white;font-size: 15px">password
didn't match
</label>
<input type="submit" value="submit" id="btn" class="button button-block" style="margin-top:20px;cursor:not-allowed"
disabled />
</form>
</div>
</div><!-- tab-content -->
</div> <!-- /form -->
Okay, so I broke down your code a bit to make it more easily understood. This example will only include your signup part of your application.
As I explained in my comment, what you could do to test the E-mails to see whether they are a Gmail or a Yahoo E-mail, is by using regular expressions (RegExp).
Example of Gmail RegExp:
/([a-zA-Z0-9]+)([\.{1}])?([a-zA-Z0-9]+)\#gmail([\.])com/g
Example of Yahoo RegExp:
/^[^#]+#(yahoo|ymail|rocketmail)\.(com|in|co\.uk)$/i
In my example, I'll put them into functions for simplicity.
Gmail RegExp function:
function regExpGmail() {
return RegExp(/([a-zA-Z0-9]+)([\.{1}])?([a-zA-Z0-9]+)\#gmail([\.])com/g);
}
Yahoo RegExp function:
function regExpYahoo() {
return RegExp(/^[^#]+#(yahoo|ymail|rocketmail)\.(com|in|co\.uk)$/i);
}
Now, I altered some of your code a bit in order to have some selectors to go by. Some of your input fields did not contain any selectors, such as name or id, while others did. So I took the liberty to add some.
One thing to note, is that the id you assigned your password input field (not the password confirm one, but the one before that) had some id conflicts. Therefore I took the liberty to change the id accordingly.
I then made a function handling all the validation logic of the input fields to fit your needs in your question. However, again, pretty simplified. I would suggest you alter it to fit your solution a little bit better, but it should give you more than a general idea.
Full Example:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Compiled and minified CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<!-- Compiled and minified JavaScript -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<script>
function regExpGmail() {
return RegExp(/([a-zA-Z0-9]+)([\.{1}])?([a-zA-Z0-9]+)\#gmail([\.])com/g);
}
function regExpYahoo() {
return RegExp(/^[^#]+#(yahoo|ymail|rocketmail)\.(com|in|co\.uk)$/i);
}
function validateInputs() {
reGmail=regExpGmail();
reYahoo=regExpYahoo();
var result = true;
var nameCheck=$('#nameField').val();
var emailCheck=$('#emailField').val();
var compDetailsCheck=$('#compDetailsField').val();
var passwordCheck=$('#passwordvz').val();
var passwordConfirmCheck=$('#passwordvConfirm').val();
if(!nameCheck) {
result=false;
$('#nameError').html('Name is missing!');
}
else {
$('#nameError').html('');
}
if(!emailCheck) {
result=false;
$('#emailError').html('E-mail is missing!');
}
else if(reGmail.test(emailCheck)) {
result=false;
$('#emailError').html('Gmail is not allowed!');
}
else if(reYahoo.test(emailCheck)) {
result=false;
$('#emailError').html('Yahoo is not allowed!');
}
else {
$('#emailError').html('');
}
if(!compDetailsCheck) {
result=false;
$('#compDetailsError').html('Company Details is missing!');
}
else {
$('#compDetailsError').html('');
}
if(!passwordCheck) {
result=false;
$('#passwordError').html('Password is missing!');
}
else {
$('#passwordError').html('');
}
if(passwordCheck != passwordConfirmCheck) {
result=false;
$('#passwordError2').html('The passwords do not match!');
}
else {
$('#passwordError2').html('');
}
if(result == true) {
$('#btn').removeAttr('disabled');
$('#btn').css("cursor", "");
alert('Everything ok, you may now press the submit button!');
}
}
</script>
<div class="form">
<div class="tab-content">
<div id="signup">
<form>
<div class="field-wrap">
<span id="nameError" style="color: red !important;"></span><br />
<label>
Name<span class="req">*</span>
</label>
<input type="text" id="nameField" required autocomplete="off" onkeyup="validateInputs();" /><br />
</div>
<div class="field-wrap">
<span id="emailError" style="color: red !important;"></span><br />
<label>
Email Address<span class="req">*</span>
</label>
<input type="email" id="emailField" required autocomplete="off" onkeyup="validateInputs();" /><br />
</div>
<div class="field-wrap">
<span id="compDetailsError" style="color: red !important;"></span><br />
<label>
Company Details<span class="req">*</span>
</label>
<input type="text" id="compDetailsField" required autocomplete="off" onkeyup="validateInputs();" /><br />
</div>
<div class="field-wrap">
<span id="passwordError" style="color: red !important;"></span><br />
<label for="passwordv">
Set A Password<span class="req">*</span>
</label>
<input id="passwordvz" type="password" class="validate" required autocomplete="off" onkeyup="validateInputs();" /><br />
</div>
<div class="field-wrap" style="margin-bottom: 0px">
<span id="passwordError2" style="color: red !important;"></span><br />
<label id="lblPasswordvConfirm" for="passwordvConfirm" data-error="Password not match"
data-success="Password Match">
Confirm Password<span class="req">*</span>
</label>
<input id="passwordvConfirm" type="password" required autocomplete="off" onkeyup="validateInputs();" /><br />
</div>
<input type="submit" value="submit" id="btn" class="button button-block" style="margin-top:20px;cursor:not-allowed" disabled />
</form>
</div>
</div><!-- tab-content -->
</div> <!-- /form -->
Screenshots of the validation process:
How to validate a multiple step form and message display for each and every fields example:please enter your email and I also want all the error message to
be display at the same time :suppose I click on next button I should display all How to validate a multiple step form and message display for each and every feilds How to validate a multiple step form and message display for each and every fields
function isEmail(str) { // simple email validation
return /(.+)#(.+){2,}\.(.+){2,}/.test($.trim(str));
}
function isEmpty(str) { // test for empty string
return $.trim(str) === "";
}
function validate($div) { // validates any div - will not let you leave the div if error
var $fields = $div.find("input"), hasError = false;
$fields.each(function() {
$(this).removeClass("error")
hasError = this.name=="pword" && isEmpty(this.value);
if (hasError) {
$("#pword").addClass("error").focus();
return false;
}
hasError = this.name=="email" && (isEmpty(this.value) || !isEmail(this.value));
if (hasError) {
$("#email").addClass("error").focus();
return false;
}
hasError = isEmpty(this.value); // the rest of the fields
if (hasError) {
$(this).addClass("error").focus();
return false;
}
})
return hasError?false:true;
}
$(function() {
// validate all divs on submit, but actually only necessary to validate thediv the submit is on
$("#myForm").on("submit",function(e) {
$(".page").each(function() {
if (!validate($(this))) {
e.preventDefault(); // stop submission
return false;
}
});
});
$(".nav").on("click", function() {
var $parent = $(this).closest("div");
var $nextDiv = $(this).hasClass("next") ? $parent.next() : $parent.prev();
if (validate($parent)) { // is the div this button is on valid?
$parent.fadeOut(function() { // fade it out and fade the next one in
if ($nextDiv.length) {
$nextDiv.fadeIn()
for (var i=$(".page").length;i> $nextDiv.index(); i--) {
$("#bar" + i).css({"background-color": "#D8D8D8"}); // we are going backwards
}
$("#bar" + $nextDiv.index()).css({"background-color": "#38610B"});
}
});
}
});
});
body {
margin: 0 auto;
padding: 0;
text-align: center;
background-color: #D8D8D8;
}
#wrapper {
width: 995px;
padding: 0px;
margin: 0px auto;
font-family: helvetica;
position: relative;
}
#wrapper .baricon {
display: inline-block;
border-radius: 100%;
padding: 12px;
background-color: #38610B;
color: white;
}
#wrapper .progress_bar {
width: 200px;
height: 5px;
border-radius: 20px;
background-color: #D8D8D8;
display: inline-block;
}
#wrapper form div {
margin-left: 340px;
padding: 10px;
box-sizing: border-box;
width: 300px;
margin-top: 50px;
background-color: #585858;
}
#wrapper form div p {
color: #F2F2F2;
margin: 0px;
margin-top: 10px;
font-weight: bold;
}
#wrapper form div .form_head {
font-size: 22px;
font-weight: bold;
margin-bottom: 30px;
}
#wrapper form div input[type="text"] {
width: 200px;
height: 40px;
padding: 5px;
border-radius: 5px;
border: none;
margin-top: 10px;
}
#wrapper form div input[type="button"],
input[type="submit"] {
width: 80px;
height: 40px;
border-radius: 5px;
border: 2px solid white;
background: none;
color: white;
margin: 5px;
margin-top: 10px;
}
#user_details,
#qualification {
display: none;
}
.error { background-color:pink !important}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div id="wrapper">
<br>
<span class='baricon'>1</span>
<span id="bar1" class='progress_bar'> </span>
<span class='baricon'>2</span>
<span id="bar2" class='progress_bar'> </span>
<span class='baricon'>3</span>
<form method="post" action="" id="myForm">
<div id="account_details" class="page">
<p class='form_head'>Account Details</p>
<p>Email Address</p>
<input type="text" name="email" id="email" placeholder='Email Address'>
<p>Password</p>
<input type="text" name="pword" id="pword" placeholder='Password'>
<br>
<input type="button" value="Next" class="nav next" />
</div>
<div id="user_details" class="page">
<p class='form_head'>User Details</p>
<p>First Name</p>
<input type="text" name="fname" id="fname" placeholder='First Name'>
<p>Last Name</p>
<input type="text" name="lname" is="lname" placeholder='Last Name'>
<p>Gender</p>
<input type="text" name="gender" id="gender" placeholder='Gender'>
<br>
<input type="button" value="Prev" class="nav prev" />
<input type="button" value="Next" class="nav next" />
</div>
<div id="qualification" class="page">
<p class='form_head'>Qualification</p>
<p>Qualification</p>
<input type="text" placeholder='Qualification'>
<p>Hobbies</p>
<input type="text" placeholder='Hobbies'>
<br>
<input type="button" value="Prev" class="nav prev" />
<input type="Submit" value="Submit">
</div>
</form>
</div>
You can use Jquery.validate.min.js file which contains validate method.
Refer the following code below:
function valid(){
$("#rform").validate({
rules:{
uname:"required", // uname, email are input names
umail:{
required:true,
email:true
},
upass:{
required:true,
minlength:8
}
},
messages:{
uname:"Please enter full name",
umail:{
required:"Please enter email id",
email:"Please enter valid email id"
},
upass:
{
required:"please provide password",
minlength:"min length of password is 8"
}
},
submitHandler :function(form){
// alert("it works!");
console.log("it works!");
// form.submit();
funreg(); //function to be called after submit button is pressed and al inputl fields are valids
}
});
}