jQuery custom validation is not working properly - javascript

I want to validate a login form. It iss working fine when I validate just mobile numbers. If I validate both mobile and password, then only the last one is working – rest is not working well. Can anybody help me, what is wrong in this code?
What I tried:
function loginValidation() {
if ($('[name="mobileNo"]').val() == '') {
$('.validation_error').text('Mobile number is reuired').addClass('validation_active');
} else {
$('.validation_error').text('').removeClass('validation_active');
}
if ($('[name="loginPassword"]').val() == '') {
$('.validation_error').text('Password is reuired').addClass('validation_active');
} else {
$('.validation_error').text('').removeClass('validation_active');
}
setTimeout(function() {
$('.validation_error').text('').removeClass('validation_active');
}, 3000);
};
.validation_error {
position: fixed;
bottom: 20px;
width: 80%;
height: auto;
text-align: center;
left: 0px;
right: 0px;
margin-left: auto;
margin-right: auto;
background: #ee2e24;
z-index: 10000;
color: #fff;
padding: 10px;
border-radius: 5px;
border: 1px solid #ccc;
box-shadow: 2px 4px 39px #333;
transition: all 0.45s;
transform: translateY(100px);
}
.validation_active {
transform: translateY(0px);
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js"></script>
<div id="loginBox">
<div class="form-group">
<div class="input-group">
<div class="input-group-append">
<span class="input-group-text"><i class="fa fa-phone"></i></span>
</div>
<input type="text" class="form-control" placeholder="Mobile No" name="mobileNo">
</div>
</div>
<div class="form-group">
<div class="input-group">
<div class="input-group-append">
<span class="input-group-text"><i class="fa fa-key"></i></span>
</div>
<input type="password" class="form-control" placeholder="Password" name="loginPassword">
</div>
</div>
<div class="form-group">
<button class="btn btn-primary btn-block btn-lg" onclick="loginVelidation();">Login</button>
</div>
</div>
<div class="validation_error"></div>
Now is password is reuired is display when i click on login button. But first i want to validate mobile is reuired

Can you try like below :
function loginVelidation()
{
if ($('[name="mobileNo"]').val() == '') {
$('.validation_error').text('Mobile number is reuired').addClass('validation_active');
}
else if ($('[name="loginPassword"]').val() == '') {
$('.validation_error').text('Password is reuired').addClass('validation_active');
else {
$('.validation_error').text('').removeClass('validation_active');
}
setTimeout(function() {
$('.validation_error').text('').removeClass('validation_active');
}, 3000);
};

Your code is right but you are overriding the error message $('.validation_error') if you want to show both errors then you to create separate error holder element.

Related

Using localStorage to remember closed state of pop-up box

I'm having difficulty implementing localStorage on my site (https://www.reclaimdesign.org).
What I am trying to do is:
Newsletter subscription pop-up on each page - this works fine
Click X to close the subscription pop-up - this also works fine
Remember the closed state of the window so that all other pages visited on our site don't have the pop-up and irritate the user after they have closed the pop-up already - this is not working. Not even a little bit.
My thinking was to set a variable with localStorage and then refer to the variable to see if the windows should be displayed or not. It is highly likely that my logic and syntax are at best sketchy, so if anyone could please guide me in the correct method this would be much appreciated.
The code I have been tinkering with for the subscription pop-up looks like this:
<script>
function setSignup(val) {
localStorage.setItem("popState", val);
}
function getSignup() {
$(window).on("load", function() {
if(localStorage.getItem("popState") == 'hide'){
//$(".signup").hide();
$(".signup").css("display", "none");
}
else if (localStorage.getItem("popState") != 'hide'){
$(".signup").css("display", "block");
}
});
}
</script>
<div class="signup">
<div class="signup-header">Sustainable Living</div>
<span class="closebtn" onclick="setSignup('hide');this.parentElement.style.display='none';">×</span>
<div class="signup-container">
<p>Get new articles related to <em>sustainability</em> and <em>eco-friendly home decor</em> direct to your inbox. We respect your privacy.</p>
<form action="https://reclaimdesign.us9.list-manage.com/subscribe/post?u=0c1d87de694b90628655f4ab9&id=bab84d57de" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" rel="noopener" novalidate>
<div id="mc_embed_signup_scroll">
<div class="mc-field-group">
<input type="email" value="" name="EMAIL" class="required email" id="mce-EMAIL" placeholder="Please Enter Your Email Address" required autocomplete="email">
</div>
<div id="mce-responses" class="clear">
<div class="response" id="mce-error-response" style="display:none"></div>
<div class="response" id="mce-success-response" style="display:none"></div>
</div>
<div style="position: absolute; left: -5000px;" aria-hidden="true"><input type="text" name="b_0c1d87de694b90628655f4ab9_bab84d57de" tabindex="-1" value=""></div>
<div class="clear"><input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
</div>
</form>
</div>
</div>
Yes your getSignup is not called correctly.
Here you can see the alternative solution without jquery.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<script>
function setSignup(val) {
localStorage.setItem("popState", val);
}
function getSignup() {
if (localStorage.getItem("popState") == 'hide') {
//$(".signup").hide();
document.querySelector('.signup').style.display = 'none';
} else if (localStorage.getItem("popState") != 'hide') {
document.querySelector('.signup').style.display = 'block';
}
}
window.addEventListener("load", getSignup);
</script>
<div class="signup">
<div class="signup-header">Sustainable Living</div>
<span class="closebtn" onclick="setSignup('hide');this.parentElement.style.display='none';">×</span>
<div class="signup-container">
<p>Get new articles related to <em>sustainability</em> and <em>eco-friendly home decor</em> direct to your inbox. We respect your privacy.</p>
<form action="https://reclaimdesign.us9.list-manage.com/subscribe/post?u=0c1d87de694b90628655f4ab9&id=bab84d57de" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" rel="noopener" novalidate>
<div id="mc_embed_signup_scroll">
<div class="mc-field-group">
<input type="email" value="" name="EMAIL" class="required email" id="mce-EMAIL" placeholder="Please Enter Your Email Address" required autocomplete="email">
</div>
<div id="mce-responses" class="clear">
<div class="response" id="mce-error-response" style="display:none"></div>
<div class="response" id="mce-success-response" style="display:none"></div>
</div>
<div style="position: absolute; left: -5000px;" aria-hidden="true"><input type="text" name="b_0c1d87de694b90628655f4ab9_bab84d57de" tabindex="-1" value=""></div>
<div class="clear"><input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
</div>
</form>
</div>
</div>
</body>
</html>
Thanks very much for your input guys. I got it working with the following (for anyone who might come up against the same issue)...
HTML:
<div class="signup">
<div class="signup-header">Sustainable Living</div>
<div class="signup-container">
<p>Get new articles related to <em>sustainability</em> and <em>eco-friendly home decor</em> direct to your inbox. We respect your privacy.</p>
<form action="https://reclaimdesign.us9.list-manage.com/subscribe/post?u=0c1d87de694b90628655f4ab9&id=bab84d57de" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" rel="noopener" novalidate>
<div id="mc_embed_signup_scroll">
<div class="mc-field-group">
<input type="email" value="" name="EMAIL" class="required email" id="mce-EMAIL" placeholder="Please Enter Your Email Address" required autocomplete="email">
</div>
<div id="mce-responses" class="clear">
<div class="response" id="mce-error-response" style="display:none"></div>
<div class="response" id="mce-success-response" style="display:none"></div>
</div> <!-- real people should not fill this in and expect good things - do not remove this or risk form bot signups-->
<div style="position: absolute; left: -5000px;" aria-hidden="true"><input type="text" name="b_0c1d87de694b90628655f4ab9_bab84d57de" tabindex="-1" value=""></div>
<div class="clear"><input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
</div>
</form>
</div>
</div>
CSS:
.signup {
bottom: 2%;
display: none;
margin-right: -15px !important;
max-width: 280px;
position: fixed;
right: 2%;
z-index: 9999;
}
.signup-header {
background: #539c22;
border-radius: 10px 10px 0 0;
color: #ffffff;
font-family: 'Carrois Gothic', sans-serif;
font-size: 20px;
padding: 25px 15px;
text-transform: uppercase;
}
.signup-container {
background-color: #6db240;
border-radius: 0 0 10px 10px;
color: #ffffff;
padding: 15px;
}
.closebtn {
color: #ffffff;
cursor: pointer;
font-size: 30px;
position: absolute;
right: 15px;
top: 5px;
}
.closebtn:hover {
color: #6db240;
}
.signup-container .button {
background-color: #539c22;
border: 0 none;
border-radius: 5px;
color: #ffffff !important;
cursor: pointer;
font-size: 15px;
height: 32px;
line-height: 32px;
margin: 0 15px 0 0 !important;
text-align: center;
transition: all 0.23s ease-in-out 0s;
width: 100% !important;
}
.signup-container .button:hover {
opacity: 0.7;
}
.signup-container .mc-field-group input {
display: block;
padding: 8px 0;
text-indent: 2%;
width: 100%;
}
.signup-container input {
border: 1px solid #d0d0d0;
border-radius: 5px;
cursor: auto;
font-family: 'Open sans', sans-serif;
font-size: 15px;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
}
JQuery:
$(document).ready(function() {
$('.signup').css('display', 'block');
$PopUp = $('.signup');
var hide = JSON.parse(localStorage.getItem('hide'));
if (hide) {
$PopUp.hide();
} else {
// initialize value in case it hasn't been set already
localStorage.setItem('hide', false);
}
$('.closebtn').click(function() {
$('.signup' ).hide();
// toggle the boolean by negating its value
var hide = JSON.parse(localStorage.getItem('hide'));
localStorage.setItem('hide', !hide);
});
});

How to validate without allowing gmail and yahoo while user signing up?

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:

Duplicate elements that has same class and put them below themselves?

UPDATED: I include this codepen becuase I'm having issue with snippet
https://codepen.io/ddcreate/pen/RJqOxo
I made this layout using bootstrap 4
What I want to achieve is when click on the "add new item", a new empty row will insert below. Since the site needs to be responsive, it's not possible to put all labels in a row and the fields in another row, otherwise the page will be messed up on smaller screen.
I found some posts about how to clond and insert using jQuery, I tried them but my issue is still here.
I hard code some script, not elegant, and they are not doing exactly what I want. The layout is messed up.
here is the code:
//add empty item fields
let addRow = $('.add-item');
//when click add fields
addRow.on('click', function() {
let newRow = $('.need-to-dup').clone(),
target = $('.need-to-dup').parent();
target[0].append(newRow[0]);
target[1].append(newRow[1]);
target[2].append(newRow[2]);
target[3].append(newRow[3]);
//console.log(newRow, newRow[3])
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section class="item-form">
<div class="row">
<div class="col-lg-2 col-md-6">
<label for="quanty">Quanty</label>
<input class="need-to-dup" type="text" name="quanty" value="">
</div>
<div class="col-lg-4 col-md-6">
<label for="item">Item</label>
<input class="need-to-dup" type="text" name="item" value="">
</div>
<div class="col-lg-4 col-md-6">
<label for="comment">Comment</label>
<input class="need-to-dup" type="text" name="comment">
</div>
<div class="col-lg-2 col-md-6">
<label for="remove">Remove</label>
<button class="need-to-dup remove-item-button btn-block btn-outline-secondary" type="button" name="remove">
<i class="fa fa-trash-o" aria-hidden="true"></i>
</button>
</div>
</div>
<div class="add-item">
<p>Add Another Item</p>
</div>
</section>
Here is my solution:
Clone the .row element using .clone()
Use .find() to find any labels and remove them from the clone
.append() that clone into the .item-form element.
//add empty item fields
let addRow = $('.add-item');
//when click add fields
let original = $('.row');
addRow.on('click', function() {
let clone = $(original).clone();
$(clone).find('label').remove();
$('.item-form').append(clone);
})
body {
font-family: 'Quicksand', sans-serif;
}
nav {
background: #66a6ff;
background-image: linear-gradient(120deg, #66a6ff 0%, #89f7fe 100%);
line-height: 70px;
color: #fff;
font-size: 24px;
font-weight: 700;
box-shadow: 0px 0px 51px 0px rgba(0, 0, 0, 0.08), 0px 6px 18px 0px rgba(0, 0, 0, 0.05)
}
button, .add-item {
transition: all .2s ease-in-out;
}
/* ***
Customer & Delivery Info Styling
*** */
input, .select-driver {
width: 100%;
margin-bottom: .5rem;
height: 40px;
}
.form-control {
border-color: #a9a9a9;
}
fieldset {
background-color: white;
border: 1px solid #e9ecef;
border-radius: 10px;
padding: 5px 20px 18px;
margin: 20px auto;
box-shadow: 0 6px 15px rgba(36,37,38,0.08);
}
legend {
font-size: 18px;
width: auto;
padding: 0 15px;
text-align: center;
}
#recurring-checkbox {
position: relative;
top: -8px;
}
input[type=checkbox] {
display: inline-block;
margin-bottom: 0;
width: 30px;
height: 30px;
background-repeat: no-repeat;
background-position: center center;
background-size: contain;
-webkit-appearance: none;
outline: 0;
border: none;
}
input[type=checkbox]:checked {
background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" x="0px" y="0px" viewBox="0 0 512 512" enable-background="new 0 0 512 512" xml:space="preserve"><path id="checkbox-3-icon" fill="#FD6585" d="M81,81v350h350V81H81z M227.383,345.013l-81.476-81.498l34.69-34.697l46.783,46.794l108.007-108.005 l34.706,34.684L227.383,345.013z"/></svg>');
}
input[type=checkbox]:not(:checked) {
background-image: url('data:image/svg+xml;utf8,<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 512 512" enable-background="new 0 0 512 512" xml:space="preserve"> <path id="checkbox-9-icon" fill="#f68ba2" d="M391,121v270H121V121H391z M431,81H81v350h350V81z"></path> </svg>');
}
/* ***
Items Detail Styling
*** */
.add-item {
border: 3px dashed;
font-size: 16px;
color: #C3C3C3;
text-align: center;
margin: 20px 0;
}
.add-item p {
margin: 0 auto;
line-height: 40px;
}
.add-item:hover {
color: #989898;
background-color: rgba(215, 214, 214, 0.56);
cursor: pointer;
}
/* ***
Notes and Buttons Styling
*** */
textarea {
height: auto;
width: 100%;
margin-bottom: 0;
}
.save-button {
border: 1px solid;
border-radius: 5px;
font-size: 18px;
font-weight: 500;
line-height: 40px;
box-shadow: 0 6px 15px rgba(36,37,38,0.08);
margin: 20px auto;
}
.save-button:hover {
background-color: #66a6ff;
border-color: #66a6ff;
}
.remove-item-button {
color: #f68ba2;
border: 1px solid #a9a9a9;
border-radius: 5px;
height: 40px;
}
.remove-item-button:hover {
color: #eee;
background-color: #f68ba2;
border-color: #fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js"></script>
<link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.css" rel="stylesheet"/>
<section class="item-form">
<div class="row">
<div class="col-lg-2 col-md-6">
<label for="quanty">Quanty</label>
<input class="need-to-dup" type="text" name="quanty" value="">
</div>
<div class="col-lg-4 col-md-6">
<label for="item">Item</label>
<input class="need-to-dup" type="text" name="item" value="">
</div>
<div class="col-lg-4 col-md-6">
<label for="comment">Comment</label>
<input class="need-to-dup" type="text" name="comment">
</div>
<div class="col-lg-2 col-md-6">
<label for="remove">Remove</label>
<button class="need-to-dup remove-item-button btn-block btn-outline-secondary" type="button" name="remove">
<i class="fa fa-trash-o" aria-hidden="true"></i>
</button>
</div>
</div>
</section>
<div class="add-item">
<p>Add Another Item</p>
</div>
It's hard to tell what you want to do. Your "messed up" display looks good to me, and is how I would make mine look. If you are trying to duplicate the entire row though (labels and all):
addRow.on('click', function() {
let newRow = $('.row')[0].clone();
newRow.appendTo($('.item-form')[0]);
});
Instead of duplicating each item, duplicate the whole row at once.
//add empty item fields
let addRow = $('.add-item');
//when click add fields
addRow.on('click', function() {
let lastRow = $('.row').last()
lastRow.after(lastRow.clone());
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section class="item-form">
<div class="row">
<div class="col-lg-2 col-md-6">
<label for="quanty">Quanty</label>
<input class="need-to-dup" type="text" name="quanty" value="">
</div>
<div class="col-lg-4 col-md-6">
<label for="item">Item</label>
<input class="need-to-dup" type="text" name="item" value="">
</div>
<div class="col-lg-4 col-md-6">
<label for="comment">Comment</label>
<input class="need-to-dup" type="text" name="comment">
</div>
<div class="col-lg-2 col-md-6">
<label for="remove">Remove</label>
<button class="need-to-dup remove-item-button btn-block btn-outline-secondary" type="button" name="remove">
<i class="fa fa-trash-o" aria-hidden="true"></i>
</button>
</div>
</div>
<div class="add-item">
<p>Add Another Item</p>
</div>
</section>
I think the best solution for you is:
Clone div.row
Change name attribute with an index (it could be quite problematic)
Remove label from the clone's element
I did this easy example:
$(document).ready(function(){
$(".add-item").on("click", function() {
var rows = $(".row","section.item-form"),
first = rows.first(), last = rows.last(), clone = first.clone();
console.log(first);
clone.insertAfter(last).find("[name!=''][name]").each(function() {
var name = $(this).attr("name").split("-")[0];
$(this).siblings("label").remove();
$(this).attr("name", name + "-" + rows.length);
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<section class="item-form">
<div class="row">
<div class="col-lg-2 col-md-6">
<label for="quanty-0">Quanty</label>
<input class="need-to-dup" type="text" name="quanty-0" value="" >
</div>
<div class="col-lg-4 col-md-6">
<label for="item-0">Item</label>
<input class="need-to-dup" type="text" name="item-0" value="" >
</div>
<div class="col-lg-4 col-md-6">
<label for="comment-0">Comment</label>
<input class="need-to-dup" type="text" name="comment-0">
</div>
<div class="col-lg-2 col-md-6">
<label for="remove-0">Remove</label>
<button class="need-to-dup remove-item-button btn-block btn-outline-secondary" type="button" name="remove-0">
<i class="fa fa-trash-o" aria-hidden="true"></i>
</button>
</div>
</div>
<div class="add-item">
<p>Add Another Item</p>
</div>
</section>
Or you can watch it in this fiddle
**.find("[name!=''][name]")** : attr *name* must exist and has to have some value
.siblings : jquery description [here][2]
.clone : jquery description [here][2]
Hope it will help.

End After Start Input Form Onchange OnClick

I have to put two dates (Start and End of task).
I would like to guarantee that the user cannot send wrong data.
My problem is, after my possible solution, the user cannot type inside date_end.
I created two javascript to do this, but I'm not javascript experienced to be sure exactly how to do this.
function datestart(value) {
document.getElementById("date_end").value = value;
}
function dateend(value) {
var vdatestart = document.getElementById("date_start").value;
if (value < vdatestart) {
document.getElementById("date_end").value = vdatestart;
}
}
.col-30 {
float: left;
width: 30%;
margin-top: 6px;
}
.col-70 {
float: left;
width: 70%;
margin-top: 6px;
}
.container {
border-radius: 5px;
background-color: #f2f2f2;
padding: 20px;
}
.row:after {
display: table;
clear: both;
}
<div class="container">
<form name="form1" action="datetime1.php" method="post">
<div class="row">
<div class="col-30">
<label>Start Date and Time from Start:</label>
</div>
<div class="col-70">
<input type='datetime-local' name='date_start' id='date_start' min='2018-05-01T00:00' max='2018-05-22T08:00' required value='2018-05-22T08:00' onchange="datestart(this.value);" onclick="datestart(this.value);" />
</div>
</div>
<div class="row">
<div class="col-30">
<label>End Date and Time:</label>
</div>
<div class="col-70">
<input type='datetime-local' name='date_end' id='date_end' min='2018-05-01T00:00' max='2018-05-22T08:00' required value='2018-05-22T08:00' onchange="dateend(this.value);" onclick="dateend(this.value);" />
</div>
</div>
<div class="row">
<input type="submit" name="submit" value="Send">
</div>
</form>
</div>

Login validation function

I have been trying to get this to work for a while now. I cannot connect the login function to the form.
I have tried onsubmit on both the form tag and the button input tag, i have tried onclick but it does not get the code from js function.
index1.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Google maps</title>
<meta name="viewport" content="initial-scale=1.0">
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<!--<link rel="http://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">-->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="util.js"></script>
<script src="JavaScript.js"></script>
<script type="text/javascript"></script>
<style>
#container {
width: 1200px;
}
#map {
width: 80%;
min-height: 600px;
/*float: right;*/
margin-top: 15px;
margin-left: auto;
margin-right: auto;
}
#img {
width: 150px;
height: 150px;
float: left;
margin-top: auto;
}
/*sökruta*/
#searchBox {
background-color: #ffffff;
padding: 5px;
font-family: 'Roboto','sans-serif';
margin-bottom: 10px;
float: top;
}
/*
html, body {
height: 100%;
margin: 0;
padding: 0;
}
*/
.search-form .form-group {
float: right !important;
transition: all 0.35s, border-radius 0s;
width: 32px;
height: 32px;
background-color: #fff;
box-shadow: 0 1px 1px rgba(0, 0, 0, 0.075) inset;
border-radius: 25px;
border: 1px solid #ccc;
}
.search-form .form-group input.form-control {
padding-right: 20px;
border: 0 none;
background: transparent;
box-shadow: none;
display:block;
}
.search-form .form-group input.form-control::-webkit-input-placeholder {
display: none;
}
.search-form .form-group input.form-control:-moz-placeholder {
/* Firefox 18- */
display: none;
}
.search-form .form-group input.form-control::-moz-placeholder {
/* Firefox 19+ */
display: none;
}
.search-form .form-group input.form-control:-ms-input-placeholder {
display: none;
}
.search-form .form-group:hover,
.search-form .form-group.hover {
width: 100%;
border-radius: 4px 25px 25px 4px;
}
.search-form .form-group span.form-control-feedback {
position: absolute;
top: -1px;
right: -2px;
z-index: 2;
display: block;
width: 34px;
height: 34px;
line-height: 34px;
text-align: center;
color: #3596e0;
left: initial;
font-size: 14px;
}
.form-group {
max-width: 300px;
margin-right: auto;
margin-left: auto;
}
</style>
</head>
<body id="container">
<img id="img" src="http://www2.math.su.se/icsim/images/sterik.jpg" alt="Stockholm"/>
<div class="row">
<br>
<div class="col-md-4 col-md-offset-3">
<form action="" class="search-form">
<div class="form-group has-feedback">
<label id="Search" class="sr-only">Search</label>
<input type="text" class="form-control" name="search" id="searchField" placeholder="Sök">
<span class="glyphicon glyphicon-search form-control-feedback"></span>
</div>
</form>
</div>
<div class="form-group">
<form id="loginForm" name="loginForm" method="POST">
<label for="user">Användarnamn: </label>
<br>
<input class="form-control" type="text" id="user" name="user" required>
<br>
<label for="password">Lösenord: </label>
<br>
<input class="form-control" type="password" id="password" name="passwords" required>
<br>
<br>
<input class="form-control" type="submit" id="login" value="Logga in" onclick="login()">
</form>
</div>
<div id="map">
</div>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDNPkC40KP9lMKHUsJW7q403qnwRqYkTno&callback=initMap">
</script>
</div>
</body>
JavaScript.js
function login() {
//spara username och password i två varibler med samma namn från formet.
var username = document.getElementById("user").value;
var password = document.getElementById("password").value;
if(username === "admin"
&& password === "123" )
{
alert( "validation succeeded" );
location.href="adminView.php";
}
else
{
alert( "validation failed" );
location.href="index1.html";
}
}
I have created working JSFiddle - Please Check : https://jsfiddle.net/5w6fg52m/1/
Below Code working fine :
<script>
//just change function name as it's conflict with button id
function login1() {
//spara username och password i två varibler med samma namn från formet.
var username = document.getElementById("user").value;
var password = document.getElementById("password").value;
if(username === "admin"
&& password === "123" )
{
alert( "validation succeeded" );
location.href="adminView.php";
}
else
{
alert( "validation failed" );
location.href="index1.html";
}
return false;
}
</script>
//HTML
<div class="form-group">
<form id="loginForm" name="loginForm" method="POST">
<label for="user">Användarnamn: </label>
<br>
<input class="form-control" type="text" id="user" name="user" required>
<br>
<label for="password">Lösenord: </label>
<br>
<input class="form-control" type="password" id="password" name="passwords" required>
<br>
<br>
<input class="form-control" type="button" id="login" value="Logga in" onclick="return login1();">
</form>
</div>
-> I have created other version of JSFiddle, so you come to know conflict issue easily: https://jsfiddle.net/5w6fg52m/2/
Here i have keep function name same(login) and change ID of submit button.
You can set the submit event directly to your like
document.getElementById("loginForm").onsubmit = function() { ... };
Bellow a sample snippet :
window.onload = function(){
document.getElementById("loginForm").onsubmit = function() {
//spara username och password i två varibler med samma namn från formet.
var username = document.getElementById("user").value;
var password = document.getElementById("password").value;
if (username === "admin" &&
password === "123") {
alert("validation succeeded");
//location.href = "adminView.php";
} else {
alert("validation failed");
//location.href = "index1.html";
}
// to prevent submit
return false;
}
}
<div class="form-group">
<form id="loginForm" name="loginForm" method="POST">
<label for="user">Användarnamn: </label>
<br>
<input class="form-control" type="text" id="user" name="user" required>
<br>
<label for="password">Lösenord: </label>
<br>
<input class="form-control" type="password" id="password" name="passwords" required>
<br>
<br>
<input class="form-control" type="submit" id="login" value="Logga in">
</form>
</div>
This happens when you declare variable or function with the same name as declare before. just rename login function or rename id="login".

Categories