good evening.
I'm a beginner with JavaScript and I'm trying to recreate a specific webpage. There, exists a button that, if the login form doesn't have at least 11 elements on user and 8 on password, the button is disabled.
How can I do this with HTML and JS?
function blockButtonByUser() {
var cpfleng = document.getElementById('.iptuser').length
console.log(cpfleng)
var btnsubmit = document.getElementById('.btnsubmit')
if (cpfleng < 11) {
btnsubmit.disabled = true;
} else {
btnsubmit.disabled = false;
}
}
function blockButtonByPassword() {
var passwordlength = document.getElementById('.iptpassword').length
console.log(cpfleng)
var btnsubmit = document.getElementById('.btnsubmit')
if (passwordlength < 8) {
btnsubmit.disabled = true;
} else {
btnsubmit.disabled = false;
}
}
<header><img src="assets/white.svg" alt="logo nubank" height="80px"></header>
<div class="container">
<h2>Faça seu login</h2>
<div class="form">
<div class="user">
<label for="cpf" class='lbluser'>CPF</label>
<input type="text" name="cpf" id="cpf" class='iptuser'>
<div class="underline"></div>
</div>
<div class="password">
<label for="password" class='lblpassword'>Senha</label>
<input type="password" name="password" id="password" class='iptpassword'>
<div class="underline"></div>
</div>
<input type="submit" value="CONTINUAR" class='btnsubmit'>
</div>
<div class="footer">
<div class="esqueci">
Esqueci minha senha >
</div>
<div class="naocliente">
Ainda não sou cliente >
</div>
</div>
</div>
Thanks for the help!
Here is something like that using an eventListener:
var cpfOkay = false
var passwordOkay = false;
var btnsubmit = document.getElementsByClassName('btnsubmit')[0];
document.getElementById('cpf').addEventListener('input', function(){
btnsubmit = document.getElementsByClassName('btnsubmit')[0];
cpfOkay = false;
if (event.target.value.length >= 11) {
cpfOkay = true;
}
checkBoth();
})
document.getElementById('password').addEventListener('input', function(){
btnsubmit = document.getElementsByClassName('btnsubmit')[0];
passwordOkay = false;
if (event.target.value.length >= 8) {
passwordOkay = true;
}
checkBoth();
})
function checkBoth() {
btnsubmit.disabled = true;
btnsubmit.style.opacity = 0.5;
if (cpfOkay && passwordOkay) {
btnsubmit.disabled = false;
btnsubmit.style.opacity = 1;
}
}
<header><img src="https://placekitten.com/200/300" alt="logo nubank" height="80px"></header>
<div class="container">
<h2>Faça seu login</h2>
<div class="form">
<div class="user">
<label for="cpf" class='lbluser'>CPF</label>
<input type="text" name="cpf" id="cpf" class='iptuser'>
<div class="underline"></div>
</div>
<div class="password">
<label for="password" class='lblpassword'>Senha</label>
<input type="password" name="password" id="password" class='iptpassword'>
<div class="underline"></div>
</div>
<input type="submit" value="CONTINUAR" class='btnsubmit' disabled style="opacity:0.5">
</div>
<div class="footer">
<div class="esqueci">
Esqueci minha senha >
</div>
<div class="naocliente">
Ainda não sou cliente >
</div>
</div>
</div>
You can add event listeners for input event for both the user and password, and based on requirements you can enable or disable the button. You can refactor your code like this:
var cpf = document.getElementById('cpf')
var password = document.getElementById('password')
var btnsubmit = document.getElementById('btnsubmit')
cpf.addEventListener('input', function (evt) {
if(cpf.value.length < 11 || password.value.length < 8){
btnsubmit.disabled = true;
} else {
btnsubmit.disabled = false;
}
});
password.addEventListener('input', function (evt) {
if(cpf.value.length < 11 || password.value.length < 8){
btnsubmit.disabled = true;
} else {
btnsubmit.disabled = false;
}
});
<header><img src="assets/white.svg" alt="logo nubank" height="80px"></header>
<div class="container">
<h2>Faça seu login</h2>
<div class="form">
<div class="user">
<label for="cpf" class='lbluser'>CPF</label>
<input type="text" name="cpf" id="cpf" class='iptuser'>
<div class="underline"></div>
</div>
<div class="password">
<label for="password" class='lblpassword'>Senha</label>
<input type="password" name="password" id="password" class='iptpassword'>
<div class="underline"></div>
</div>
<input type="submit" value="CONTINUAR" class='btnsubmit' id='btnsubmit' disabled>
</div>
<div class="footer">
<div class="esqueci">
Esqueci minha senha >
</div>
<div class="naocliente">
Ainda não sou cliente >
</div>
</div>
</div>
<script src="main.js"></script>
You have a few issues. One was getElementById on classes. One was no event handler. Lastly, you were trying to get the length on the element, but not the length of the value.
This should work:
document.querySelector('.btnsubmit').addEventListener('click', e =>{
blockButtonByUser();
blockButtonByPassword()
})
function blockButtonByUser(){
var cpfleng = document.querySelector('.iptuser').value.length
console.log(cpfleng)
var btnsubmit = document.querySelector('.btnsubmit')
if (cpfleng < 11) {
btnsubmit.disabled = true;
} else{
btnsubmit.disabled = false;
}
}
function blockButtonByPassword(){
var passwordlength = document.querySelector('.iptpassword').value.length
console.log(passwordlength)
var btnsubmit = document.querySelector('.btnsubmit')
if (passwordlength < 8) {
btnsubmit.disabled = true;
} else{
btnsubmit.disabled = false;
}
}
Related
I am going to create simple validation form using Vanilla JavaScript, but I have problem, I want to check first ('entername') field, if user will not enter any letters in it, i want to console log message ('enter name'), it's works fine, but after that user reenter his name if field it returns in console ('enter name'), i want to return ('not enter') message.
var userBtn = document.getElementById('checkuserinputs');
var checkUserName = document.getElementById('user-name').value;
var checkUserSurname = document.getElementById('user-surname').value;
var checkUserPhone = document.getElementById('user-mobile').value;
userBtn.addEventListener('click', function(){
if(checkUserName.length == 0){
console.log('enter name')
}else{
console.log('not enter')
}
})
<div class="container-fluid">
<div class="modal-costum-row">
<div class="enter-name-side">
<div class="input-row">
<input class="costum--input" type="text" id="user-name" name="user-nm" placeholder="entername">
</div>
</div>
<div class="enter-surname-side">
<div class="input-row">
<input class="costum--input" type="text" id="user-surname" name="surname" placeholder="entersurname">
</div>
</div>
</div>
<div class="enter-tel-numb-side">
<div class="input-row input--wide">
<input class="costum--input" type="tel" id="user-mobile" name="user-mobile" placeholder="enterphonenumber">
</div>
</div>
</div>
<button id="checkuserinputs">check input</button>
You need to get the value after clicking the button. If you put it outside of the click event, the value will never be updated.
var userBtn = document.getElementById('checkuserinputs');
userBtn.addEventListener('click', function () {
var checkUserName = document.getElementById('user-name').value;
var checkUserSurname = document.getElementById('user-surname').value;
var checkUserPhone = document.getElementById('user-mobile').value;
if (checkUserName.length == 0) {
console.log('enter name')
} else {
console.log('not enter')
}
})
<div class="container-fluid">
<div class="modal-costum-row">
<div class="enter-name-side">
<div class="input-row">
<input class="costum--input" type="text" id="user-name" name="user-nm" placeholder="entername" />
</div>
</div>
<div class="enter-surname-side">
<div class="input-row">
<input class="costum--input" type="text" id="user-surname" name="surname" placeholder="entersurname" />
</div>
</div>
</div>
<div class="enter-tel-numb-side">
<div class="input-row input--wide">
<input class="costum--input" type="tel" id="user-mobile" name="user-mobile" placeholder="enterphonenumber" />
</div>
</div>
</div>
<button id="checkuserinputs">check input</button>
You need to retrieve the value of the input field in the click function callback:
userBtn.addEventListener('click', () => {
const checkUserName = document.getElementById('user-name').value;
if(checkUserName.length === 0){
console.log('enter name')
} else {
console.log('not enter')
}
})
change the variable geting value to button click function that is,
var userBtn = document.getElementById('checkuserinputs');
userBtn.addEventListener('click', function(){
var checkUserName = document.getElementById('user-name').value;
var checkUserSurname = document.getElementById('user-surname').value;
var checkUserPhone = document.getElementById('user-mobile').value;
if(!checkUserName){
console.log('enter name')
}else{
console.log('not enter')
}
})
var userBtn = document.getElementById('checkuserinputs');
userBtn.addEventListener('click', function(){
var checkUserName = document.getElementById('user-name').value;
var checkUserSurname = document.getElementById('user-surname').value;
var checkUserPhone = document.getElementById('user-mobile').value;
if(!checkUserName){
console.log('enter name')
}else{
console.log('not enter')
}
})
<div class="container-fluid">
<div class="modal-costum-row">
<div class="enter-name-side">
<div class="input-row">
<input class="costum--input" type="text" id="user-name" name="user-nm" placeholder="entername">
</div>
</div>
<div class="enter-surname-side">
<div class="input-row">
<input class="costum--input" type="text" id="user-surname" name="surname" placeholder="entersurname">
</div>
</div>
</div>
<div class="enter-tel-numb-side">
<div class="input-row input--wide">
<input class="costum--input" type="tel" id="user-mobile" name="user-mobile" placeholder="enterphonenumber">
</div>
</div>
</div>
<button id="checkuserinputs">check input</button>
PROBLEM: I want to click on the X (font awesome icon) and close the modal of the pop up, but it won't close.
IT ONLY WORKS ON CERTAIN BROWSERS AND CONDITIONS:
So far the x close the modal only IE and Firefox, but on Chrome and Safari browser it doesn't close at all. Another thing that works is when I type the letter "x" and don't use any other tags inside the button tag. However, I want to use the font awesome icon for design purposes.
PLEASE HELP:
I don't know much JavaScript at all, and I can't seem to solve this issue using the current modal setup for my signup/login.
Here's a Fiddle to play around with: https://jsfiddle.net/o5vpt6ck/
HTML:
<div class="cd-signin-modal js-signin-modal"> <!-- this is the entire modal form, including the background -->
<div class="cd-signin-modal__container"> <!-- this is the container wrapper -->
<ul class="p-0 cd-signin-modal__switcher js-signin-modal-switcher js-signin-modal-trigger">
<li>Sign in</li>
<li>New account</li>
</ul>
<div class="cd-signin-modal__block js-signin-modal-block" data-type="login"> <!-- log in form -->
<form id="login-form" class="cd-signin-modal__form" action="confirm" method="post">
<h3 class="bigsentence black text-center font-weight-bold">Log in</h3>
<p class="cd-signin-modal__fieldset">
<div class="sentence" id="noenter">This account doesn't exist please try again or create a new account.</div>
<label class="cd-signin-modal__label font-weight-bold cd-signin-modal__label--image-replace" for="signin-email">Enter your email or username</label>
<input class="cd-signin-modal__input cd-signin-modal__input--full-width cd-signin-modal__input--has-padding cd-signin-modal__input--has-border" required id="username" name="username" type="text" placeholder="Email or username">
</p>
<p class=" cd-signin-modal__fieldset">
<label class="cd-signin-modal__label cd-signin-modal__label--password cd-signin-modal__label--image-replace" for="signin-password">Enter your password</label>
<input required name="password" class="passpad cd-signin-modal__input cd-signin-modal__input--full-width cd-signin-modal__input--has-padding cd-signin-modal__input--has-border" id="password" type="text" placeholder="Password">
Hide
</p>
<p class="cd-signin-modal__fieldset">
<input class="cd-signin-modal__input cd-signin-modal__input--full-width" name="submit" type="submit" value="LOG IN">
</p>
</form>
<p class="m-0 cd-signin-modal__bottom-message js-signin-modal-trigger sentence">Forgot your password?</p>
</div> <!-- cd-signin-modal__block -->
<div class="cd-signin-modal__block js-signin-modal-block" data-type="signup"> <!-- sign up form -->
<form id="signup-form" class="cd-signin-modal__form" action="" method="post">
<h3 class="bigsentence black text-center font-weight-bold">Create</h3>
<p class="cd-signin-modal__fieldset">
<label class="cd-signin-modal__label cd-signin-modal__label--email cd-signin-modal__label--image-replace" for="signup-email">Enter your email address</label>
<input class="cd-signin-modal__input cd-signin-modal__input--full-width cd-signin-modal__input--has-padding cd-signin-modal__input--has-border signupfield" id="email" type="email" name="email" placeholder="Enter your email address">
</p>
<p class="cd-signin-modal__fieldset">
<input class="cd-signin-modal__input cd-signin-modal__input--full-width" name="submit" type="submit" value="GET STARTED">
</p>
</form>
</div> <!-- cd-signin-modal__block -->
<div class="cd-signin-modal__block js-signin-modal-block" data-type="reset"> <!-- reset password form -->
<form id="password-form" class="cd-signin-modal__form" action="" method="post">
<h3 style="padding:0!important; margin:0!important; height:20px!important; " class="bigsentence black text-center font-weight-bold">Reset your Password</h3>
<p class="cd-signin-modal__fieldset">
<label class="cd-signin-modal__label cd-signin-modal__label--email sentence" for="reset-email">Please enter the email address associated with your account.</label>
<input class="cd-signin-modal__input cd-signin-modal__input--full-width cd-signin-modal__input--has-padding cd-signin-modal__input--has-border" id="email" type="email" name="email" placeholder="Enter your email address">
</p>
<p class="cd-signin-modal__fieldset">
<input class="cd-signin-modal__input cd-signin-modal__input--full-width cd-signin-modal__input--has-padding" type="submit" name="submit" value="Reset password">
</p>
</form>
<p class="m-0 cd-signin-modal__bottom-message js-signin-modal-trigger">Back to log in</p>
</div> <!-- cd-signin-modal__block -->
<button type="button" class="js-close close" data-dismiss="modal" aria-label="Close">
<i style="position:absolute; top:-30px!important;" aria-hidden="true" class="text-white fas fa-times"></i>
</button>
</div> <!-- cd-signin-modal__container -->
</div> <!-- cd-signin-modal -->
<nav class="navbar navbar-expand fixed-top bg-white">
<div class="container-fluid">
</div>
<ul class="container-fluid navbar-nav js-signin-modal-trigger justify-content-end list-unstyled" id="navbar2SupportedContent">
<!-- inser more links here -->
<li>Log in</li>
<li>Sign up</li>
</ul>
</nav>
JS:
(function(){
//Login/Signup modal window - by CodyHouse.co
function ModalSignin( element ) {
this.element = element;
this.blocks = this.element.getElementsByClassName('js-signin-modal-block');
this.switchers = this.element.getElementsByClassName('js-signin-modal-switcher')[0].getElementsByTagName('a');
this.triggers = document.getElementsByClassName('js-signin-modal-trigger');
this.hidePassword = this.element.getElementsByClassName('js-hide-password');
this.init();
};
ModalSignin.prototype.init = function() {
var self = this;
//open modal/switch form
for(var i =0; i < this.triggers.length; i++) {
(function(i){
self.triggers[i].addEventListener('click', function(event){
if( event.target.hasAttribute('data-signin') ) {
event.preventDefault();
self.showSigninForm(event.target.getAttribute('data-signin'));
}
});
})(i);
}
//close modal
this.element.addEventListener('click', function(event){
if( hasClass(event.target, 'js-signin-modal') || hasClass(event.target, 'js-close') ) {
event.preventDefault();
removeClass(self.element, 'cd-signin-modal--is-visible');
}
});
//close modal when clicking the esc keyboard button
document.addEventListener('keydown', function(event){
(event.which=='27') && removeClass(self.element, 'cd-signin-modal--is-visible');
});
//hide/show password
for(var i =0; i < this.hidePassword.length; i++) {
(function(i){
self.hidePassword[i].addEventListener('click', function(event){
self.togglePassword(self.hidePassword[i]);
});
})(i);
}
//IMPORTANT - REMOVE THIS - it's just to show/hide error messages in the demo
this.blocks[0].getElementsByTagName('form')[0].addEventListener('submit', function(event){
event.preventDefault();
self.toggleError(document.getElementById('signin-email'), true);
});
this.blocks[1].getElementsByTagName('form')[0].addEventListener('submit', function(event){
event.preventDefault();
self.toggleError(document.getElementById('signup-username'), true);
});
};
ModalSignin.prototype.togglePassword = function(target) {
var password = target.previousElementSibling;
( 'password' == password.getAttribute('type') ) ? password.setAttribute('type', 'text') : password.setAttribute('type', 'password');
target.textContent = ( 'Hide' == target.textContent ) ? 'Show' : 'Hide';
putCursorAtEnd(password);
}
ModalSignin.prototype.showSigninForm = function(type) {
// show modal if not visible
!hasClass(this.element, 'cd-signin-modal--is-visible') && addClass(this.element, 'cd-signin-modal--is-visible');
// show selected form
for( var i=0; i < this.blocks.length; i++ ) {
this.blocks[i].getAttribute('data-type') == type ? addClass(this.blocks[i], 'cd-signin-modal__block--is-selected') : removeClass(this.blocks[i], 'cd-signin-modal__block--is-selected');
}
//update switcher appearance
var switcherType = (type == 'signup') ? 'signup' : 'login';
for( var i=0; i < this.switchers.length; i++ ) {
this.switchers[i].getAttribute('data-type') == switcherType ? addClass(this.switchers[i], 'cd-selected') : removeClass(this.switchers[i], 'cd-selected');
}
};
ModalSignin.prototype.toggleError = function(input, bool) {
// used to show error messages in the form
toggleClass(input, 'cd-signin-modal__input--has-error', bool);
toggleClass(input.nextElementSibling, 'cd-signin-modal__error--is-visible', bool);
}
var signinModal = document.getElementsByClassName("js-signin-modal")[0];
if( signinModal ) {
new ModalSignin(signinModal);
}
// toggle main navigation on mobile
var mainNav = document.getElementsByClassName('js-main-nav')[0];
if(mainNav) {
mainNav.addEventListener('click', function(event){
if( hasClass(event.target, 'js-main-nav') ){
var navList = mainNav.getElementsByTagName('ul')[0];
toggleClass(navList, 'cd-main-nav__list--is-visible', !hasClass(navList, 'cd-main-nav__list--is-visible'));
}
});
}
//class manipulations - needed if classList is not supported
function hasClass(el, className) {
if (el.classList) return el.classList.contains(className);
else return !!el.className.match(new RegExp('(\\s|^)' + className + '(\\s|$)'));
}
function addClass(el, className) {
var classList = className.split(' ');
if (el.classList) el.classList.add(classList[0]);
else if (!hasClass(el, classList[0])) el.className += " " + classList[0];
if (classList.length > 1) addClass(el, classList.slice(1).join(' '));
}
function removeClass(el, className) {
var classList = className.split(' ');
if (el.classList) el.classList.remove(classList[0]);
else if(hasClass(el, classList[0])) {
var reg = new RegExp('(\\s|^)' + classList[0] + '(\\s|$)');
el.className=el.className.replace(reg, ' ');
}
if (classList.length > 1) removeClass(el, classList.slice(1).join(' '));
}
function toggleClass(el, className, bool) {
if(bool) addClass(el, className);
else removeClass(el, className);
}
//credits http://css-tricks.com/snippets/jquery/move-cursor-to-end-of-textarea-or-input/
function putCursorAtEnd(el) {
if (el.setSelectionRange) {
var len = el.value.length * 2;
el.focus();
el.setSelectionRange(len, len);
} else {
el.value = el.value;
}
};
})();
Add Class name btn-js-close and include this class in your JS Condition
Working code - JSFiddle
HTML Change:
<i style="position:absolute; top:-30px!important;" aria-hidden="true" class="btn-js-close text-white fas fa-times"></i>
JS Change:
if( hasClass(event.target, 'js-signin-modal') || hasClass(event.target, 'btn-js-close') ) {
removeClass(self.element, 'cd-signin-modal--is-visible');
event.preventDefault();
}
I am having trouble figuring out how to display values from a JavaScript to a table in HTML. I am trying to display just the even numbers between a starting number and a ending number. I believe my functions are correct but for some reason the values do not display on the page when submitted. Any help would be awesome. Thanks
function clearErrors() {
for (var loopCounter = 0; loopCounter < document.forms["displayEvens"].elements.length; loopCounter++) {
if (document.forms["displayEvens"].elements[loopCounter]
.parentElement.className.indexOf("has-") != -1) {
document.forms["displayEvens"].elements[loopCounter]
.parentElement.className = "form-group";
}
}
}
function resetForm() {
clearErrors();
document.forms["displayEvens"]["startingNumber"].value = "";
document.forms["displayEvens"]["endingNumber"].value = "";
document.forms["displayEvens"]["step"].value = "";
document.getElementById("results").style.display = "none";
document.getElementById("submitButton").innerText = "DisplayEvens";
document.forms["displayEvens"]["startingNumber"].focus();
}
function displayEvens(startingNumber, endingNumber, step) {
var startingNumber =
parseInt(document.getElementById("startingNum").value);
var endingNumber = parseInt(document.getElementById("endingNum").value);
var step = parseInt(document.getElementById("stepNum").value);
var evenNums = [];
for (var i = startingNumber; i < endingNumber; i += step) {
if (i % 2 == 0) {
evenNums.push(i);
}
}
document.getElementById("evens").innerText = evenNums;
}
function validateItems() {
clearErrors();
displayEvens(startingNumber, endingNumber, step);
console.trace("got here!");
//var startingNumber = document.forms["displayEvens"]
["startingNumber"].value;
//var endingNumber = document.forms["displayEvens"]
["endingNumber"].value;
//var step = document.forms["displayEvens"]["step"].value;
if (startingNumber == "" || isNaN(startingNumber)) {
alert("Starting Number must be filled in with a number.");
document.forms["displayEvens"]["startingNumber"]
.parentElement.className = "form-group has-error";
document.forms["displayEvens"]["startingNumber"].focus();
return false;
}
if (endingNumber == "" || isNaN(endingNumber)) {
alert("Ending Number must be filled in with a number.");
document.forms["displayEvens"]["endingNumber"]
.parentElement.className = "form-group has-error"
document.forms["displayEvens"]["endingNumber"].focus();
return false;
}
if (endingNumber <= startingNumber) {
alert("Ending Number must be greater than the Starting number.");
document.forms["displayEvens"]["endingNumber"]
.parentElement.className = "form-group has-error"
document.forms["displayEvens"]["endingNumber"].focus();
return false;
}
if (step == "" || isNaN(step)) {
alert("Step Number must be filled in with a number.");
document.forms["displayEvens"]["step"]
.parentElement.className = "form-group has-error"
document.forms["displayEvens"]["step"].focus();
return false;
}
if (step < 0) {
alert("Step Number must be filled in with a positive number.");
document.forms["displayEvens"]["step"]
.parentElement.className = "form-group has-error"
document.forms["displayEvens"]["step"].focus();
return false;
}
//document.getElementById("results").style.display = "block";
//document.getElementById("submitButton").innerText = "Recalculate";
document.getElementById("startingNum").innerText =
Number(startingNumber);
document.getElementById("endingNum").innerText = Number(endingNumber);
document.getElementById("stepNum").innerText = Number(step);
document.getElementById("evens").innerText = Number(evenNums);
return false;
}
<!DOCTYPE html>
<html>
<head>
<script type="text/JavaScript" src="displayEvens.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="container">
<h1>Display Evens</h1>
<form name="displayEvens" onsubmit="return validateItems();" onreset="resetForm();">
<div class="form-group row">
<label for="startingNumber" class="col-sm-2 col-form-
label">Starting Number</label>
<div class="col-sm-10">
<input type="number" class="form-control" ` id="startingNumber" ` placeholder="Enter a number" />
</div>
</div>
<div class="form-group row">
<label for="endingNumber" class="col-sm-2 col-form-`
label">Ending`
Number</label>
<div class="col-sm-10">
<input type="number" class="form-control" id="endingNumber" placeholder="Enter a number" />
</div>
</div>
<div class="form-group row">
<label for="step" class="col-sm-2 col-form-
label">Step</label>
<div class="col-sm-10">
<input type="number" class="form-control" id="step" placeholder="Enter a number" />
</div>
</div>
<button type="submit" id="submitButton" class="btn btn-
default">Display Evens</button>
<button type="reset" id="resetButton" class="btn">Reset</button>
</form>
</br>
<table id="results" class="table table-striped">
<thead>
<tr>
<td>Even numbers between <span id="startingNum"></span> and
<span id="endingNum"></span> by <span id="stepNum"></span></td>
<th>Result</th>
</tr>
</thead>
<tbody>
<tr>
<td><span id="evens"></span></td>
</tbody>
</table>
</div>
<!--<div id="results" style="display:none;">
<h3>Results:</h3>
<span id="evens"></span>
<h3>Your Starting Number:</h3>
<span id="start"></span></br>
<h3>Your Ending Number:</h3>
<span id="end"></span></br>
<h3>Your Step Number:</h3>
<span id="step"></span>
</div>-->
</body>
</html>
There's a fundamental issue wrong with your html. You are using the same id attribute on multiple elements. The id attribute should be used only on one element because it is a unique identifier.
Also when you have cleaned that up you can change your line
document.getElementById("endingNum").innerText = Number(endingNumber);
replace it with
document.getElementById("endingNum").append(Number(endingNumber))
instead
After clicking submit the form is not producing errors next to the input fields ,it refreshes the page and clears all the fields.
HTML:
<form id="mc-form" method="POST">
<div class="form-group col-xs-12 ">
<label for="name" hidden>שם פרטי</label>
<input type="text" name="name" id="name" class="cv form-control" placeholder="שם פרטי" onkeyup='validateMessage()'>
<span class='error-message' id='name-error'></span>
</div>
<div class="form-group col-xs-12 ">
<label for="lastName" hidden>שם משפחה</label>
<input type="text" name="lastName" id="lastName" class="cv form-control" placeholder="שם משפחה" onkeyup='validateMessage()'>
<span class='error-message' id='name-error'></span>
</div>
<div class="form-group col-xs-12 ">
<label for="phone" hidden>טלפון</label>
<input type="text" name="phone" id="phone" class="cv form-control" placeholder="טלפון" onkeyup='validateMessage()'>
<span class='error-message' id='name-error'></span>
</div>
<div class="form-group col-xs-12 ">
<label for="email" hidden>דואר אלקטרוני</label>
<input type="email" name="email" id="email" class="cv form-control" placeholder="דואר אלקטרוני" onkeyup='validateMessage()'>
<span class='error-message' id='name-error'></span>
</div>
<div class="form-group col-xs-12 ">
<label for="subject" hidden>נושא</label>
<input type="text" name="subject" id="subject" class="cv form-control" placeholder="נושא" onkeyup='validateMessage()'>
</div>
<div class="form-group col-xs-12 ">
<label for="message" hidden>הודעה</label>
<textarea name="message" id="message" class="cv form-control message" placeholder="השאירו את הודעתכם פה" rows="4" cols="50" onkeyup='validateMessage()'></textarea>
</div>
<!-- <input type="submit" id="submit-button" class="btn btn-custom-outline " value="שלח" > -->
<button onclick='return validateForm()' class="btn btn-custom-outline " id="submit-button">שלח</button>
<span class='error-message' id='submit-error'></span>
<br>
<!-- <div class="success"><?= $success ?></div>-->
<!--<span class="error"></span> -->
</form>
My JavaScript:
function validateName() {
var name = document.getElementById('name').value;
if(name.length == 0) {
producePrompt('Name is required', 'name-error' , 'red')
return false;
}
if (!name.match( /^[a-zא-ת]+(\s[a-zא-ת]+)*$/i)) {
producePrompt('Letters only please.','name-error', 'red');
return false;
}
producePrompt('Valid', 'name-error', 'green');
return true;
}
function validatePhone() {
var phone = document.getElementById('phone').value;
if(phone.length == 0) {
producePrompt('Phone number is required.', 'phone-error', 'red');
return false;
}
if(!phone.match(/^[0-9]{10}$/)) {
producePrompt('Only digits, please.' ,'phone-error', 'red');
return false;
}
producePrompt('Valid', 'phone-error', 'green');
return true;
}
function validateEmail () {
var email = document.getElementById('email').value;
if(email.length == 0) {
producePrompt('Email Invalid','email-error', 'red');
return false;
}
if(!email.match(/^[A-Za-z\._\-[0-9]*[#][A-Za-z]*[\.][a-z]{2,4}$/)) {
producePrompt('Email Invalid', 'email-error', 'red');
return false;
}
producePrompt('Valid', 'email-error', 'green');
return true;
}
/*function validateMessage() {
var message = document.getElementById('contact-message').value;
var required = 30;
var left = required - message.length;
if (left > 0) {
producePrompt(left + ' more characters required','message-error','red');
return false;
}
producePrompt('Valid', 'message-error', 'green');
return true;
}*/
function validateForm() {
if (!validateName() || !validatePhone() || !validateEmail() ) {
jsShow('submit-error');
producePrompt('Please fix errors to submit.', 'submit-error', 'red');
setTimeout(function(){jsHide('submit-error');}, 2000);
return false;
}
else {
}
}
function jsShow(id) {
document.getElementById(id).style.display = 'block';
}
function jsHide(id) {
document.getElementById(id).style.display = 'none';
}
function producePrompt(message, promptLocation, color) {
document.getElementById(promptLocation).innerHTML = message;
document.getElementById(promptLocation).style.color = color;
}
My scrips are in index.html , same page the form is, in the end :
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" ></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" ></script>
<script src="js/bootstrap.min.js" ></script>
<!-- [ SLIDER SCRIPT ] -->
<script type="text/javascript" src="js/SmoothScroll.js"></script>
<script src="js/script.js" ></script>
<script src="js/validateform.js" ></script>
After clicking submit the form is not producing errors next to the input fields ,it refreshes the page and clears all the fields.
The issue that you are running into in calling
producePrompt('Email Invalid','email-error', 'red');
and any other where you are not passing name-error an error is occurring as there is no element with the id email-error they all have the same id. When the error is thrown the function returns undefined instead of false causing the form to be submitted.
When using Chrome dev tools you can go into settings and check preserve log this will allow you to see errors even after the page refreshes.
As to checking for all errors instead of just the first one...
the if (!validateName() || !validatePhone() || !validateEmail() ) {
or statements here mean the first one that false causes the rest to not be checked. Instead you could do something like the following
var vn = validateName();
var vp = validatePhone();
var ve = validateEmail();
if (!vn || !vp || !ve) {
I'm trying to work out the percentage value for each field in a form. However my current code is only working out the value for the first field or whichever one is focused.
I'd like it so that the percentage value only for the filed in the same fieldset
The current code works but i'd like to apply to to multiple fieldsets without them interfering with other inputs on the same page
In the snippet you can see that the two separate amounts which are editing each others details
function percentageCal() {
var $price = $(".form-item--invamt .form-item__input").on("input", calculatePerc),
$percentage = $(".form-item__input-expand .percentage").on("input", calculatePrice),
$currency = $(".form-item__input-expand .currency").on("focus", removePercent),
$none = $(".form-item--charges .no-charge").on("focus", removePercent),
$increase = $(".wrapper-types__percentage-value"),
$increaseWrap = $(".wrapper-types__percentage");
$($percentage).add($currency).keypress(function(event) {
if (event.which != 8 && event.which != 0 && (event.which < 48 || event.which > 57)) {
return false;
}
});
function calculatePrice() {
var percentage = parseFloat($(this).val());
var price = parseFloat($price.val());
var calcPrice = parseFloat((price * percentage / 100).toFixed(2));
var newPrice = price + calcPrice;
$increase.text(newPrice);
$increaseWrap.fadeIn();
if (isNaN(newPrice)) {
$increaseWrap.hide();
}
}
function calculatePerc() {
var percentage = $percentage.val();
var price = parseFloat($(this).val());
var calcPerc = parseFloat((price * percentage / 100).toFixed(2));
var newPrice = price + calcPerc;
$increase.text(newPrice);
}
function removePercent() {
$increaseWrap.fadeOut();
}
}
percentageCal();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<fieldset class="wrapper-types__investment">
<legend class="sr-only">Investment 1</legend>
<div class="form-item form-item--required form-item--invamt">
<label class="form-item__label" for="wrappers[0]">Investment amount</label>
<div class="form-item__input-labelled">
<span class="form-item__input-label">£</span>
<input class="form-item__input " type="number" name="wrappers[0]" id="wrappers[0]" min="0" value="15000" required>
</div>
</div>
<div class="form-item form-item--charges-wrap">
<span class="form-item__label">Charges</span>
<div class="form-item form-item--charges">
<label class="form-item__input-label-expand" for="percentage1">%</label>
<div class="form-item__input-expand">
<input class="form-item__input percentage" type="number" name="percentage" id="percentage1">
</div>
</div>
</div>
<div class="form-item form-item--charges-wrap">
<span class="wrapper-types__percentage">= £<span class="wrapper-types__percentage-value"></span></span>
</div>
<div class="form-item form-item--action-btns">
</div>
</fieldset>
<fieldset class="wrapper-types__investment">
<legend class="sr-only">Investment 2</legend>
<div class="form-item form-item--required form-item--invamt">
<label class="form-item__label" for="wrappers[1]">Investment amount</label>
<div class="form-item__input-labelled">
<span class="form-item__input-label">£</span>
<input class="form-item__input " type="number" name="wrappers[1]" id="wrappers[1]" min="0" value="13005.02" required>
</div>
</div>
<div class="form-item form-item--charges-wrap">
<span class="form-item__label">Charges</span>
<div class="form-item form-item--charges">
<label class="form-item__input-label-expand" for="percentage2">%</label>
<div class="form-item__input-expand">
<input class="form-item__input percentage" type="number" name="percentage" id="percentage2">
</div>
</div>
</div>
<div class="form-item form-item--charges-wrap">
<span class="wrapper-types__percentage">= £<span class="wrapper-types__percentage-value"></span></span>
</div>
<div class="form-item form-item--action-btns">
</div>
</fieldset>
Instead of IDs, use classes and DOM traversal functions to find the fields in the same fieldset.
function percentageCal() {
var $price = $(".form-item--invamt .form-item__input").on("input", calculatePerc),
$percentage = $(".form-item__input-expand .percentage").on("input", calculatePrice),
$currency = $(".form-item__input-expand .currency").on("focus", removePercent),
$none = $(".form-item--charges .no-charge").on("focus", removePercent),
$increase = $(".wrapper-types__percentage-value"),
$increaseWrap = $(".wrapper-types__percentage");
$percentage.add($currency).keypress(function(event) {
if (event.which != 8 && event.which != 0 && (event.which < 48 || event.which > 57)) {
return false;
}
});
function calculatePrice() {
var $fieldset = $(this).closest("fieldset");
var percentage = parseFloat($(this).val());
var price = parseFloat($fieldset.find(".form-item--invamt .form-item__input").val());
var calcPrice = parseFloat((price * percentage / 100).toFixed(2));
var newPrice = price + calcPrice;
$fieldset.find(".wrapper-types__percentage-value").text(newPrice);
$fieldset.find(".wrapper-types__percentage").fadeIn();
if (isNaN(newPrice)) {
$fieldset.find(".wrapper-types__percentage").hide();
}
}
function calculatePerc() {
var $fieldset = $(this).closest("fieldset");
var percentage = $fieldset.find(".form-item__input-expand .percentage").val();
var price = parseFloat($(this).val());
var calcPerc = parseFloat((price * percentage / 100).toFixed(2));
var newPrice = price + calcPerc;
$fieldset.find(".wrapper-types__percentage-value").text(newPrice);
}
function removePercent() {
var $fieldset = $(this).closest("fieldset");
$fieldset.find(".wrapper-types__percentage").fadeOut();
}
}
percentageCal();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<fieldset class="wrapper-types__investment">
<div class="form-item--invamt">
<div>
<span class="form-item__input-label">£</span>
<input class="form-item__input " type="number" name="wrappers[0]" id="wrappers[0]" min="0" value="15000" required>
</div>
</div>
<div class="form-item--charges-wrap">
<div class="form-item--charges">
<label class="form-item__input-label-expand" for="percentage">%</label>
<div class="form-item__input-expand">
<input class="form-item__input percentage" type="number" name="percentage" id="percentage">
</div>
</div>
</div>
<div class="form-item--charges-wrap">
<span class="wrapper-types__percentage">= £<span class="wrapper-types__percentage-value"></span></span>
</div>
</fieldset>
<fieldset class="wrapper-types__investment">
<div class="form-item--invamt">
<div>
<span class="form-item__input-label">£</span>
<input class="form-item__input " type="number" name="wrappers[1]" id="wrappers[1]" min="0" value="15000" required>
</div>
</div>
<div class="form-item--charges-wrap">
<div class="form-item--charges">
<label class="form-item__input-label-expand" for="percentage1">%</label>
<div class="form-item__input-expand">
<input class="form-item__input percentage" type="number" name="percentage" id="percentage1">
</div>
</div>
</div>
<div class="form-item--charges-wrap">
<span class="wrapper-types__percentage">= £<span class="wrapper-types__percentage-value"></span></span>
</div>
</fieldset>