JS Problem with Multiple Forms working using 1 JS file - javascript

This is following on from:
JS Form validation Checkbox IF statement not working
I've added another separate form for the business owners.
Currently I have a separate html file for 'business' & 'customer'. I've put the CSS for both forms in one file and also the JS is all in one file.
Problem : I seem to only be able to get one form to work at the moment, although if I take the forms out and separate them into different projects they work fine, independently, on different platforms or workspaces.
What I'm trying to do is get the one JS file to reference both forms & execute commands based on what page the user is on filling out the form (business or customer). The problem is only Customer Form works when the JS is all in one file, the Business Form doesn't work (ie show the red highlighted errors). If I take the Business Form out and put it in another stand alone project (inc the HTML, CSS & JS) it works fine. Seems to be a conflict with the Form reference?
I need 2 forms as I will be expanding on fields etc, but to keep things simple I've thrown up samples of both on here.
Here is the HTML for the 'Business' form, (customer form HTML is in the link -and yes it has been changed to work properly):
<div class="business-contactus-body">
<div class="business_container">
<div class="business_contactus_heading_form">
<h2>Business client Form</h2>
</div>
<form id="business_contactus_form" class="business_contactus_form">
<div class="business-form-control">
<label for="businessName">Name</label>
<input type="text" placeholder="ABC Company" id="businessName" />
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<small>Error message</small>
</div>
<div class="business-form-control">
<label for="businessEmail">Email</label>
<input type="text" placeholder="a#abccompany.com" id="businessEmail" />
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<small>Error message</small>
</div>
<div class="business-form-control">
<label for="businessMessage">Message</label>
<textarea type="text" placeholder="Please enter a brief message" id="businessMessage" cols="30" rows="10"></textarea>
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<small>Error message</small>
</div>
<div class="business-form-control">
<input class="businessDisclaimerBox" type="checkbox" id="businessDisclaimerBox" />
<label for="businessDisclaimerBox" id="disclaimer-label">I agree to the terms and conditions.</label>
<small>Error message</small>
</div>
<button class="contactus_form_button">Submit</button>
</form>
</div>
</div>
CSS - for both forms
/***** CONTACT US PAGE CSS *****/
* {
box-sizing: border-box;
}
.customer-contactus-body, business-contactus-body {
min-height: 1300px;
width: 100%;
background-color: pink;
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
margin: 0px;
}
.customerCU-contactus-heading-message, .business-contactus-heading-message {
width: 600px;
font-weight: 200;
margin: -50px 0px 50px 20px;
padding: 0px;
}
.customerCU_container, .business_container {
background-color: grey;
border-radius: 5px;
overflow: hidden;
width: 600px;
max-width: 100%;
}
.customer_contactus_heading_form, .business_contactus_heading_form {
border-bottom: 1px solid #f0f0f0;
background-color: white;
padding: 20px 40px;
}
.customer_contactus_heading_form h2, .business_contactus_heading_form h2 {
margin: 0px;
color: black;
}
.contactus_form, .business_contactus_form {
padding: 30px 40px;
}
.customerCU-form-control, .business-form-control {
margin-bottom: 10px;
padding-bottom: 20px;
position: relative;
}
.customerCU-form-control label, .business-form-control label {
display: inline-block;
margin-bottom: 5px;
font-weight: 530;
font-size: 17px;
}
.customerCU-form-control input, .business-form-control input {
border: 2px solid #f0f0f0;
border-radius: 4px;
display: block;
font-size: 14px;
padding: 10px;
width: 100%;
}
.customerCU-form-control input:focus, .business-form-control input:focus {
outline: 0;
border-color: grey;
}
.customerCU-form-control.success input, .business-form-control.success input {
border-color: green;
}
.customerCU-form-control textarea, .business-form-control textarea {
resize: vertical;
border: 2px solid #f0f0f0;
border-radius: 4px;
display: block;
font-size: 14px;
padding: 10px;
width: 100%;
}
.customerCU-form-control.error input, .business-form-control.error input {
border-color: red;
}
.customerCU-form-control textarea:focus, .business-form-control textarea:focus {
outline: 0;
border-color: grey;
}
.customerCU-form-control.success textarea, .business-form-control.success textarea {
border-color: green;
}
.customerCU-form-control.error textarea, .business-form-control.error textarea {
border-color: red;
}
.customerCU-form-control.error label#disclaimer-label, .business-form-control.error label#disclaimer-label {
color: red;
font-weight: bold;
text-decoration: underline;
}
.customerCU-form-control i, .business-form-control i {
visibility: hidden;
position: absolute;
top: 40px;
right: 10px;
}
.customerCU-form-control.success i.fa-check-circle, .business-form-control.success i.fa-check-circle {
color: green;
visibility: visible;
}
.customerCU-form-control.error i.fa-exclamation-circle, .business-form-control.error i.fa-exclamation-circle {
color: red;
visibility: visible;
}
.customerCU-form-control small, .business-form-control small {
color: red;
position: absolute;
bottom: 0;
left: 0;
visibility: hidden;
}
.customerCU-form-control.error small, .business-form-control.error small {
visibility: visible;
}
label#disclaimer-label {
margin-left: 10px;
font-size: 12px;
width: 612px;
}
.contactus_form_button {
background-color: rgb(31, 136, 229);
border: 2px solid rgb(128, 128, 128, 0.199);
border-radius: 4px;
color: #fff;
display: block;
font-size: 16px;
padding: 10px;
margin-top: 20px;
width: 100%;
cursor: pointer;
transition: 0.3s ease background-color;
}
.contactus_form_button:hover {
cursor: pointer;
box-shadow: 1px 1px 1px rgb(25, 60, 173);
}
#keyframes contactus-form-status {
0% {
opacity: 1;
pointer-events: all;
}
90% {
opacity: 1;
pointer-events: all;
}
100% {
opacity: 0;
pointer-events: none;
}
}
JS
//** CUSTOMER FORM **//
const form = document.getElementById('contactus_form');
const customerName = document.getElementById('customerName');
const customerCUEmail = document.getElementById('customerCUEmail');
const disclaimerBox = document.getElementById('disclaimerBox');
form.addEventListener('submit', e => {
e.preventDefault();
checkInputs();
});
function checkInputs() {
// trim to remove the whitespaces
const customerNameValue = customerName.value.trim();
const customerCUEmailValue = customerCUEmail.value.trim();
if(customerNameValue === '') {
setErrorFor(customerName, 'Please enter your name');
} else {
setSuccessFor(customerName);
}
if(customerCUEmailValue === '') {
setErrorFor(customerCUEmail, 'Email cannot be blank');
} else if (!isEmail(customerCUEmailValue)) {
setErrorFor(customerCUEmail, 'Not a valid email');
} else {
setSuccessFor(customerCUEmail);
}
if(!disclaimerBox.checked == true){
setErrorFor(disclaimerBox, 'Please check box and accept our terms and conditions.');
}else {
setSuccessFor(disclaimerBox);
}
}
function setErrorFor(input, message) {
const formControl = input.parentElement;
const small = formControl.querySelector('small');
formControl.className = 'customerCU-form-control error';
small.innerText = message;
}
function setSuccessFor(input) {
const formControl = input.parentElement;
formControl.className = 'customerCU-form-control success';
}
function isEmail(customerCUEmail) {
return /^(([^<>()\[\]\\.,;:\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,}))$/.test(customerCUEmail);
}
// ** BUSINESS CLIENT FORM **
const business_contactus_form = document.getElementById('business_contactus_form');
const businessName = document.getElementById('businessName');
const businessEmail = document.getElementById('businessEmail');
const businessMessage = document.getElementById("businessMessage");
const businessDisclaimerBox = document.getElementById('businessDisclaimerBox');
business_contactus_form.addEventListener('submit', e => {
e.preventDefault();
checkbusiness_Inputs();
});
function checkbusiness_Inputs() {
//trim to remove the whitespaces
const businessNameValue = businessName.value.trim();
const businessEmailValue = businessEmail.value.trim();
const businessMessageValue = businessMessage.value.trim();
if (businessNameValue === '') {
setErrorForB(businessName, 'Please enter your name');
} else {
setSuccessForB(businessName);
}
if (businessEmailValue === '') {
setErrorForB(businessEmail, 'Email cannot be blank');
} else if (!isEmailB(businessEmail)) {
setErrorForB(businessEmail, 'Not a valid email');
} else {
setSuccessForB(businessEmail);
}
if (businessMessageValue === '') {
setErrorForB(businessMessage, 'Please enter a message.');
} else {
setSuccessForB(businessMessage);
}
if (!businessDisclaimerBox.checked) {
setErrorForB(businessDisclaimerBox, 'Please check box and accept terms and conditions.');
} else {
setSuccessForB(businessDisclaimerBox);
}
}
function setErrorForB(input, message) {
const formControlB = input.parentElement;
const small = formControlB.querySelector('small');
formControlB.className = 'business-form-control error';
small.innerText = message;
}
function setSuccessForB(input) {
const formControlB = input.parentElement;
formControlB.className = 'business-form-control success';
}
function isEmailB(businessEmail) {
return /^(([^<>()\[\]\\.,;:\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,}))$/.test(businessEmail);
}

Related

How to change active tab back to not active after validation failure in JavaScript

I have a Details tab with a dropdown that swaps forms in and out and a Result tab that displays the result in a graph. When the user selects "Result" I want to validate the data entry before going to the result tab.
What happens is that when the Result tab is clicked it becomes active and changes color. I then goes into script.js displayResultContent() which validates the data entry. If the data is not valid I don't want to proceed to the result tab so I only show the result if the data is okay.
The issue I have is that if the data is invalid, error messages are displayed on the form, but the Result tab remains displayed with the active color instead of changing to the non active color. Once the user clicks the mouse on the screen the tab changes color.
Is there any way to make this tab change to the non active color without having to click on the screen? I haven't yet put the media queries in so this looks best on a wide screen, otherwise the tabs are displayed below each other instead of beside. It still works though.
const DATE_TYPE_PAST = 0;
const DATE_TYPE_FUTURE = 1;
const SUCCESS = 0;
const ERROR = 1;
$(function() {
$('#details-tab').click(displayDetails);
$('#result-tab').click(displayResultContent);
$("#your-details-tab").click(displayYourDetailsTab);
$("#your-superannuation-tab").click(displayYourSuperannuationTab);
});
function displayYourDetailsTab() {
removeAllForms();
var form = $("#your-details-form");
form.show();
$('#details-tab').html("Your Details");
}
function displayYourSuperannuationTab() {
removeAllForms();
var form = document.getElementById("your-superannuation-form");
form.style.display = 'block';
$('#details-tab').html("Your Superannuation");
}
function removeAllForms() {
var forms = document.getElementsByTagName('form');
for (var i = 0; i < forms.length; i++) {
forms[i].style.display = "none";
}
}
function displayDetails() {
$('#details').show();
$('#result').hide();
$('#result-tab').removeClass('active');
$('#details-tab').addClass('active');
}
function displayResultContent() {
// FIRST CHECK DATA ENTRY
const dateResult = checkDate(document.getElementById("date-of-birth"), DATE_TYPE_PAST);
const rentResult = checkMandatoryWholeNumber(document.getElementById("fortnightly-rent"), "Fortnightly rent ", 0, 999);
if (dateResult === SUCCESS && rentResult === SUCCESS) {
$('#result').show();
$('#details').hide();
$('#result-tab').addClass('active');
$('#details-tab').removeClass('active');
}else {
$('#result-tab').removeClass('active');
}
}
const showError = (input, message) => {
// get the form-field element
let formField = input.closest(".form-field");
// add the error class
formField.classList.remove('success');
formField.classList.add('error');
// show the error message
const error = formField.querySelector('small');
error.textContent = message;
};
const showSuccess = (input) => {
// get the form-field element
let formField = input.closest(".form-field");
// remove the error class
formField.classList.remove('error');
formField.classList.add('success');
// hide the error message
const error = formField.querySelector('small');
error.textContent = '';
};
const yourDetailsForm = document.getElementById("your-details-form");
if (yourDetailsForm != null) {
yourDetailsForm.addEventListener('input', function(e) {
switch (e.target.id) {
case 'date-of-birth':
checkDate(document.getElementById(e.target.id), DATE_TYPE_PAST);
break;
case 'fortnightly-rent':
checkMandatoryWholeNumber(document.getElementById(e.target.id), "Fortnightly rent ", 0, 999);
break;
}
});
}
const isRequired = value => value !== '';
const isValidDate = function(date) {
return (date !== "Invalid Date") && date !== ("Nan");
}
function checkDate(dateElement, dateType) {
const val = dateElement.value;
const newDate = new Date(val);
if (isValidDate(newDate)) {
const today = new Date();
today.setHours(0,0,0,0);
if (dateType === DATE_TYPE_PAST) {
if (newDate < today) {
// okay
showSuccess(dateElement);
return SUCCESS;
}else {
// error
showError(dateElement, "date must be in the past");
return ERROR;
}
} if (dateType === DATE_TYPE_FUTURE) {
if (newDate >= today) {
// okay
showSuccess(dateElement);
return SUCCESS;
}else {
// error
showError(dateElement, "date must be in the future");
return ERROR;
}
}
}else {
showError(dateElement, "date is mandatory");
return ERROR;
}
}
$(document).on("keydown", ".whole-number", function (e) {
const invalidChars = [
"-",
"+",
"e",
".",
];
if (invalidChars.includes(e.key)) {
e.preventDefault();
}
});
function checkMandatoryWholeNumber(element, prefix, min, max) {
if (!isRequired(element.value)) {
showError(element, prefix + " is mandatory");
return ERROR;
}
const val = parseInt(element.value);
if (val < min || val > max) {
showError(element, prefix + " must be between " + min + " and " + max);
return ERROR;
}
showSuccess(element);
return SUCCESS;
}
html, body {
height: 100%;
margin: 0;
overflow:hidden;
}
.content {
height:100%;
margin-left: 15%;
margin-right: 15%;
display:flex;
flex-flow: column;
}
.content .result-content {
background-color: #FFF;
flex: 1 1 auto;
margin-left:1%;
margin-right:1%;
display: none;
}
#tabs {
width: 70%;
margin: 0 auto;
padding: 0;
border-bottom: 7px solid #FE6D73;
margin-top: 50px;
}
.form-container {
width: 70%;
height: 98%;
background-color: #FFF;
margin: 0 auto;
overflow-y: auto;
overflow-x: hidden;
padding-bottom: 7px;
box-sizing: border-box;
padding-top: 0px;
}
li {
list-style: none;
}
/*******************************************************************/
/* NAV TABS */
/******************************************************************/
.nav-link {
border-radius: 15px 15px 0px 0px !important;
text-decoration: none;
height: 40px;
font-size: 80%;
background-color: #eeeeee !important;
color: #aaaaaa;
}
.nav-link.active,
.nav-link:active,
.nav-link:hover,
.nav-link:focus {
border-radius: 15px 15px 0px 0px !important;
background-color: #FE6D73 !important;
color: #FEF9EF !important;
}
.nav-link-left {
width: 255px;
}
.nav-link-right {
width: 100px;
}
.nav-tabs>li>ul>li>a {
width: 200px;
}
.dropdown-menu {
z-index: 999999;
}
.nav-tabs>li>ul {
background-color: #FE6D73 !important;
}
/* Remove border from tabs */
.nav-tabs .nav-link {
border: 0px solid transparent;
}
/* This is the dropdown link */
.dropdown-item {
background-color: #FE6D73 !important;
color: #FEF9EF !important;
}
/* Border at bottom of each item in the drop down list */
.dropdown-menu>li {
border-bottom: 1px solid #FEF9EF !important;
}
.nav-tabs>li>ul>li.active>a, .nav-tabs>li>ul>li.active>a:focus, .nav-tabs>li>ul>li>a:hover {
background-color: #FEF9EF !important;
color: #FE6D73 !important;
}
.dropdown-menu {
border-top: 1px solid #FEF9EF;
}
/*******************************************************************/
/* FORMS */
/******************************************************************/
input[type="number"] {
/*80px*/
width: 5em;
font-size: 80%;
}
input[type="date"] {
border: 1px solid #cccccc;
}
input {
border: 1px solid #cccccc;
}
#your-superannuation-form {
display: none;
}
form {
margin-top: 20px;
background-color: beige;
}
.form-group {
margin-top: 20px;
}
.disabled-link {
cursor: not-allowed;
opacity: 0.5;
}
.disabled-text {
opacity: 0.5;
}
.enabled-text {
opacity: 1.0;
}
.enabled-link {
cursor: pointer;
opacity: 1.0;
}
.pointer-not-allowed{
cursor: not-allowed;
}
.pointer-allowed {
cursor: pointer;
}
form label {
font-family: 'opensansreg', 'Verdana', 'Arial';
}
.form-text {
font-family: Georgia;
align-self: start;
}
.button-text {
font-family: Georgia;
font-size:80%;
}
.input-text {
font-family: Consolas, Lucida Console, monospace;
}
:root {
--error-color: #dc3545;
--success-color: #cccccc;
--warning-color: #ffc107;
}
.form-field input:focus {
outline: none;
}
.form-field.error input {
/* border-color: var(--error-color); */
border: 1px solid #dc3545;
}
.form-field.success input {
/* border-color: var(--success-color); */
border: 1px solid #cccccc;
}
.form-field small {
color: var(--error-color);
font-size: 70%;
display: block;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="style.css"/>
</head>
<body>
<div id="tabs">
<ul class="nav nav-tabs">
<li class="dropdown nav-item">
<a class="nav-link nav-link-left dropdown-toggle active" id="details-tab" data-bs-toggle="dropdown" href="#" role="button" aria-expanded="false">Details</a>
<ul class="dropdown-menu">
<li><a class="dropdown-item" id="your-details-tab" href="#">Your Details</a></li>
<li><a class="dropdown-item" id="your-superannuation-tab" href="#">Your Superannuation</a></li>
</ul>
</li>
<li class="nav-item">
<a class="nav-link nav-link-right" id="result-tab" href="#" tabindex="-1">Result</a>
</li>
</ul>
</div>
<div class="content">
<div class="form-container" id="details">
<form id="your-details-form">
<div class="form-group">
<label for="date-of-birth" class="form-text">Date of Birth</label>
<div class="form-field">
<input type="date" class="form-text" id="date-of-birth" name="date-of-birth">
<small></small>
</div>
</div>
<div class="form-group">
<label for="fortnightly-rent" class="form-text">Fortnightly Rent</label>
<div class="form-field">
<input type="text" class="input-text" size="4" id="fortnightly-rent" name="fortnightly-rent"
onKeyDown="if (this.value.length == 4) this.value = this.value.slice(0, -1);"/>
<small></small>
</div>
</div>
</form>
<form id="your-superannuation-form">
THIS IS YOUR SUPERANNUATION FORM
</form>
</div> <!-- end form-container-->
<div class="result-content" id="result">
THIS IS THE RESULT
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js#3.8.0/dist/chart.min.js"></script>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
Please remove the .nav-link:focus selector from this declaration
.nav-link.active,
.nav-link:active,
.nav-link:hover{
border-radius: 15px 15px 0px 0px !important;
background-color: #FE6D73 !important;
color: #FEF9EF !important;
}
Currently when you click on a tab the focus remains and it goes only after clicking away
.nav-link.active,
.nav-link:active,
.nav-link:hover,
.nav-link:focus <---- It works properly after removing this
{
border-radius: 15px 15px 0px 0px !important;
background-color: #FE6D73 !important;
color: #FEF9EF !important;
}

How to fix CSS height transition so it fluidly goes back to place

Any time I have elements within my div ".packagebuilder" get class ".shown" added it adds code to fluidly transition. It works when the pricing table appears but not when all the other elements come into view. When ".hidden" gets added it should fluidly go back into place, but it doesn't transition at all, just immediately flashes back. What am I missing? Appreciate any help.
.hidden {
opacity: 0;
max-height: 0px;
transition: max-height 0s cubic-bezier(0, 1, 0, 1) 0s;
position:absolute;
top:-100000px;
}
.shown {
opacity: 1;
max-height: 1000px;
transition: max-height 1s ease-in-out 0s;
position:relative;
}
This is the code. Anything with the class "hidden" will get "shown" added onclick of an input.
var seoSelect = document.querySelector("select#seo");
var designSelect = document.querySelector("select#design");
var anySelect = document.querySelector(".packagebuilder select");
var seoOption = document.querySelector(".seo.option");
var designOption = document.querySelector(".design.option");
var anyOption = document.querySelector(".packagebuilder .option");
var estimateTable = document.querySelector(".estimate");
//Price Table Items
var seofirstmonthitem = document.querySelector(".item.seofirstmonth");
var seosetupfeeitem = document.querySelector(".item.setupfee");
var designdeposititem = document.querySelector(".item.designdeposit");
var designpayoffitem = document.querySelector(".item.designpayoff");
var seomonthlyitem = document.querySelector(".item.seomonthly");
var dueToday = document.querySelector(".today #val");
var dueLater = document.querySelector(".later #val");
var dueMonthly = document.querySelector(".monthly #val");
function hidePriceTable() {
$(estimateTable).addClass("hidden");
$(estimateTable).removeClass("shown");
$(".disclaimer.pricing").addClass("hidden");
$(".disclaimer.pricing").removeClass("shown");
$(".button.package").addClass("hidden");
$(".button.package").removeClass("shown");
}
function showPriceTable() {
$(estimateTable).removeClass("hidden");
$(estimateTable).addClass("shown");
$(".disclaimer.pricing").removeClass("hidden");
$(".disclaimer.pricing").addClass("shown");
$(".button.package").removeClass("hidden");
$(".button.package").addClass("shown");
}
function HideSE0() {
$(seoOption).addClass("hidden");
$(seoOption).removeClass("shown");
}
function ShowSEO() {
$(seoOption).addClass("shown");
$(seoOption).removeClass("hidden");
}
function HideDesign() {
$(designOption).addClass("hidden");
$(designOption).removeClass("shown");
}
function ShowDesign() {
$(designOption).addClass("shown");
$(designOption).removeClass("hidden");
}
function hideSEOcontent() {
$(".item.seofirstmonth").hide();
$(".item.seomonthly").hide();
$(".item.setupfee").hide();
$('select#seo').prop('selectedIndex', null);
$("input#seosetup").val("0");
$("input#seovalue").val("0");
HideSE0();
}
function showSEOcontent() {
$(".item.seofirstmonth").show();
$(".item.seomonthly").show();
$(".item.setupfee").show();
ShowSEO();
}
function hideDesigncontent() {
$(".item.designdeposit").hide();
$(".item.designpayoff").hide();
$('select#design').prop('selectedIndex', null);
$("input#designdeposit").val("0");
$("input#designpayoff").val("0");
$("input#designtotal").val("0");
HideDesign();
}
function showDesigncontent() {
$(".item.designdeposit").show();
$(".item.designpayoff").show();
ShowDesign();
}
function hideAll() {
hideSEOcontent();
hidePriceTable();
HideDesign();
HideSE0();
}
hideAll();
$(function () {
setInterval(constantChecker, 1);
});
/// Web Design Package Choices + Pricing /////////////////////////////////////////////////
function designSelectValues() {
// Set Default values
$('select#design').prop('selectedIndex', null);
//Check for new package choice
$(designSelect).change(function () {
if (designSelect.value == "1") {
$("input#designdeposit").val("1500");
$("input#designpayoff").val("1500");
$("input#designtotal").val("3000");
} else if (designSelect.value == "2") {
$("input#designdeposit").val("2500");
$("input#designpayoff").val("2500");
$("input#designtotal").val("5000");
} else if (designSelect.value == "3" || designSelect.value == "0" ) {
$("input#designdeposit").val("0");
$("input#designpayoff").val("0");
$("input#designtotal").val("0");
} else {
$("input#designdeposit").val("1500");
$("input#designpayoff").val("1500");
$("input#designtotal").val("3000");
}
});
}
/// SEO Package Choices + Pricing /////////////////////////////////////////////////
function seoSelectValues() {
// Set Default values
$('select#seo').prop('selectedIndex', null);
//Check for new package choice
$(seoSelect).change(function () {
if (seoSelect.value == "1") {
$("input#seosetup").val("500");
$("input#seovalue").val("750");
} else if (seoSelect.value == "2") {
$("input#seosetup").val("1000");
$("input#seovalue").val("1500");
} else if (seoSelect.value == "3") {
$("input#seosetup").val("1500");
$("input#seovalue").val("2500");
} else if (seoSelect.value == "4" || seoSelect.value == "0" ) {
$("input#seosetup").val("0");
$("input#seovalue").val("0");
} else {
$("input#seosetup").val("500");
$("input#seovalue").val("750");
}
});
}
// When service added, activate options and values ////////////////////////////////////
$('#chooseseo').change(function () {
if (!$('#chooseseo').is(':checked')) {
hideSEOcontent();
$("input#seosetup").val("0");
$("input#seovalue").val("0");
} else if ($('#chooseseo').is(':checked')) {
showSEOcontent();
seoSelectValues();
}
});
$('#choosedesign').change(function () {
if (!$('#choosedesign').is(':checked')) {
hideDesigncontent();
$("input#designdeposit").val("0");
$("input#designpayoff").val("0");
$("input#designtotal").val("0");
} else if ($('#choosedesign').is(':checked')) {
showDesigncontent();
designSelectValues();
}
});
// Convert String to US Currency ///////////////////////////////////////////////////////////
var formatter = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
});
// Constanly check for new numbers /////////////////////////////////////////////////////////////
function constantChecker() {
// Show or Hide Custom Disclaimer ///
// if ($(seoSelect).val() == "4" || $(designSelect).val() == "3") {
// $(".disclaimer.custom").show();
// } else if ($(seoSelect).val() != "4" || $(designSelect).val() != "3") {
// $(".disclaimer.custom").hide();
// }
if (($("select#design")[0].selectedIndex === 0) && ($("select#seo")[0].selectedIndex === 0)) {
hidePriceTable();
}
else {
showPriceTable();
}
// Get Current Select Values /////
var currentSeoSetup = $("input#seosetup").val();
var currentSeoValue = $("input#seovalue").val();
var currentDesignDeposit = $("input#designdeposit").val();
var currentDesignPayoff = $("input#designpayoff").val();
var currentDueToday = formatter.format(+currentDesignDeposit + +currentSeoSetup + +currentSeoValue);
var currentDueLater = formatter.format(+currentDesignPayoff);
var currentMonthly = formatter.format(+currentSeoValue);
// Format individual Items ///
var seoSetupVal = formatter.format(+currentSeoSetup);
var seoMonthlyVal = formatter.format(+currentSeoValue);
var DesignDepositVal = formatter.format(+currentDesignDeposit);
var DesignPayoffVal = formatter.format(+currentDesignPayoff);
// Apply Current Values /////
$(dueToday).text(currentDueToday);
$(dueLater).text(currentDueLater);
$(dueMonthly).text(currentMonthly);
$(".setupfee span#val").text(seoSetupVal);
$(".seofirstmonth span#val").text(seoMonthlyVal);
$(".seomonthly span#val").text(seoMonthlyVal);
$(".designdeposit span#val").text(DesignDepositVal);
$(".designpayoff span#val").text(DesignPayoffVal);
}
/// Submit Button
$('.packagebuilder').on('submit', function (e) {
e.preventDefault();
var formData = $(this).serialize();
var fullUrl = window.location.href;
var finalUrl = fullUrl + "?&" + formData;
//window.location.href = finalUrl;
alert(finalUrl);
});
.hidden {
opacity: 0;
max-height: 0px;
transition: max-height 0s cubic-bezier(0, 1, 0, 1) 0s;
position:absolute;
top:-100000px;
}
.shown {
opacity: 1;
max-height: 1500px;
transition: max-height 1s ease-in-out 0s;
position:relative;
}
.packagebuilder {
max-width: 700px;
margin: auto;
box-sizing: border-box;
}
form .services {
display:
flex;
/* grid-gap: 30px; */
box-sizing: border-box;
/* padding-bottom: 20px; */
flex-direction: column;
width: auto;
}
form .option {display: flex;grid-gap: 10px;border-radius: 20px;padding-top: 30px;flex-direction: column;}
.services label {
font-size: 22px;
position: relative;
color: black;
font-weight:600!important;
}
.services select {
padding: 15px!important;
height: auto;
font-size: 20px!important;
padding-right: 45px!important;
font-weight: 300;
border-radius: 5px;
appearance: none;
-webkit-appearance:none;
overflow-wrap: break-word;
background: #ffffff;
border: solid 2px #e0e0e0!important;
}
.services select {
background-image: url("https://static1.squarespace.com/static/5ee80dfeb418dc785b48ee76/t/62ec6656067dab5da9df2fa0/1659659862901/angle-down-solid.svg");
background-size: 20px;
background-position: right 15px center;
background-repeat: no-repeat;
}
.services option {}
.services select:focus {
outline:none!important;
}
.estimate {
display: flex;
flex-direction: column;
/* background: linear-gradient(180deg, #eeeeee, transparent); */
margin: 30px 0px 20px;
overflow: hidden;
border-top: solid 1px #000000;
}
.figure {
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px 0px;
border-bottom: solid 1px #dedede;
}
.figure span:first-child {
font-weight:600
}
.figure span:last-child {
font-size: 20px;
}
.figure:last-child {
border:none;
}
#val {
font-weight:600!important;
padding: 0;
border-radius: 5px;
}
.today #val {font-size: 30px;}
.figure.today {
color: black;
}
.figure {
}
.packagebuilder .disclaimer {
background: #f9f6e6;
padding: 10px;
display: flex;
align-items: center;
justify-content: center;
text-align: left;
font-size: 14px;
grid-gap: 10px;
}
.disclaimer i {
color: #ff9d00;
font-size: 20px;
}
.packagebuilder input.package {
background: #000000!important;
border: none!important;
color: white;
margin-top: 20px!important;
}
.packagebuilder input.package:hover {
background: var(--mainbrand)!important;
}
label.choose {
display:
block;
line-height:40px;
height:40px;
width: fit-content;
cursor: pointer;
min-width: 150px;
font-weight: 300!important;
pointer-events: all;
border-radius: 10px;
-webkit-font-smoothing: antialiased;
margin-top: 10px;
font-family:
Arial,Helvetica,sans-serif;
color: gray!important;
text-align:
center;
background: #e4e4e4;
padding: 1px 15px;
/* box-shadow: 11px 14px 20px #0000001a; */
}
label.add-label {
font-weight:600;
}
input.choose[type=checkbox] {
display: none;
}
input.choose:checked + label {
color: #ffffff!important;
background:
var(--mainbrand);
box-shadow: none;
}
.figure.item {
padding: 0px 20pxpx;
}
.figure.item span, .item span#val {
font-size: 13px;
font-weight: 300!important;
}
.today.item span#val, .today.item span {
color: #656565;
}
.other.item span#val, .other.item span {
color:#6c7674;
}
.today.item {
/* background: #f4f4f4!important; */
}
.other.item {
/* background: #f4f4f4!important; */
}
/* new stuff */
.packcheck {
visibility: hidden;
}
input.choose:checked + label .check {
visibility: visible;
}
input.choose.checkbox:checked + label:before {
content: "";
}
.addservices {
padding-bottom: 20px;
border-bottom: solid 1px #c0c0c0;
}
.flex-options {
display: flex;
justify-content: flex-start;
flex-wrap: wrap;
grid-gap: 10px;
}
:root {
--mainbrand: #006eff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="packagebuilder">
<div class="services">
<div class="addservices">
<label class="add-label">Add Services</label>
<div class="flex-options" name="addservices">
<div>
<input class="choose" id="chooseseo" type="checkbox" name="chooseseo">
<label for="chooseseo" class="choose">SEO</label>
</div>
<div>
<input class="choose" id="choosedesign" type="checkbox" name="choosedesign">
<label for="choosedesign" class="choose">Web Design</label>
</div></div></div>
<div class="seo option hidden">
<label for="seo">Pick your SEO Package</label>
<select type="text" id="seo" name="seo">
<option value="0" disabled selected value>-- Select an Option --</option>
<option value="1" class="one">Gold – $750 per month, $500 setup fee</option>
<option value="2">Essentials – $1500 per month, $1000 setup fee</option>
<option value="3">Local Authority – $2500 per month, $1500 setup fee</option>
</select>
</div>
<div class="design option hidden">
<label for="design">Pick your Design Package</label>
<select type="text" id="design" name="design">
<option value="0" disabled selected value>-- Select an Option --</option>
<option value="1">Vanity – $3000, $1500 deposit</option>
<option value="2">Lux – $5000, $2500 deposit</option>
</select>
</div>
</div><div class="estimate hidden">
<span class="figure today"><span>Due Today: </span><span id="val"></span>
</span><span class="figure today item setupfee" style="display:none;"><span style="">SEO Setup Fee</span><span id="val" style=""></span></span>
<span class="figure today item seofirstmonth" style="display:none;"><span style="">SEO First Month</span><span id="val" style=""></span></span><span class="figure today item designdeposit" style="display:none;"><span style="">Web Design 50% Deposit</span><span id="val" style=""></span></span><span class="figure later"><span>Due Later: </span><span id="val"></span></span><span class="figure other item designpayoff" style="display:none;"><span style="">Web Design Payoff</span><span id="val" style=""></span></span>
<span class="figure monthly"><span>Recurring Starting Next Month: </span><span id="val"></span></span><span class="figure other item seomonthly" style="display:none;"><span style="">SEO Monthly Fee</span><span id="val" style=""></span></span>
</div>
<div class="disclaimer pricing hidden"><i class="fas fa-exclamation-circle"></i>This is only an estimate before the final proposal. The final pricing will be reflected on an e-signature agreement we will send you.</div>
<div class="disclaimer custom" style="
display: none;
"><i class="fas fa-exclamation-circle"></i>Since you chose "Custom" on one of the options, the numbers may not reflect what you have discussed with us. Only choose this option if you spoke with us about a custom package prior.</div><input type="hidden" id="seovalue" name="seovalue" value="">
<input type="hidden" id="seosetup" name="seosetup" value=""><input type="hidden" id="designdeposit" name="designdeposit" value=""><input type="hidden" id="designpayoff" name="designpayoff" value="">
<input type="hidden" id="designtotal" name="designtotal" value=""><input type="submit" value="Continue" class="button package hidden">
</form>

Requesting assistance troubleshooting HTML forms/cards

I am currently working on an exercise in HTML/CSS/JS. The premise is a library website. The idea is that I have a collapsable form that when deployed allows the user to enter the title of the book, the author, and page numbers. When submit is clicked it takes the user input and generates a html card on the webpage. This title card will display the user input information along with a slider to denote if it was read or not.
I have a few test cards generated in my code that creates the cards as intended, however when utilizing the html form i can not seem to get additional cards to create. I ran some tests to the console to ensure that the form is in fact capturing the user input and assigning it.
If anyone could point me in the right direction that would be amazing. I have been messing with this issue for almost 2 weeks with no luck. I have a feeling that my "wires" are not connected right in the javascript. Thank you in advance.
Javascript:
// set up library
let myLibrary = [];
//set up object
function Book(title, author, pages) {
this.title = title;
this.author = author;
this.pages = pages;
}
//add object to library
function addBookToLibrary(Book){
myLibrary.push(Book);
}
//test books
const lotr = new Book('The Fellowship of the Ring', 'J.R.R. Tolkein', '423 pages');
const ender = new Book('Enders Game', 'Orson Scott Card', '324 pages');
const martian = new Book('The Martian', 'Anthony Weir', '369 pages');
addBookToLibrary(lotr);
addBookToLibrary(ender);
addBookToLibrary(martian);
//inject html to create cards
let htmlCode = ``;
myLibrary.forEach(function(singleBookObjects){
htmlCode =
htmlCode +
`
<entry>
<div>
<h3>Title: ${singleBookObjects.title}</h3>
<h3>Author: ${singleBookObjects.author}</h3>
<h3>Pages: ${singleBookObjects.pages}</h3>
<label class="switch">
<input type="checkbox">
<span class="slider round"></span>
</label>
</div>
</entry>
`;
});
function newBookCard() {
let newdiv = document.createElement('div');
newdiv.className+= 'item';
let newp = document.createElement('p');
newp.innerHTML = "Title";
newdiv.appendChild(newp);
document.getElementById('main').appendChild(newdiv);
}
const addBtn = document.getElementById("submit");
addBtn.onclick = function() {
let a = document.getElementById("bookTitle").value
let b = document.getElementById("bookAuthor").value
let c = document.getElementById("bookPages").value
let newBook = new Book(a, b, c);
addBookToLibrary(newBook);
console.log(myLibrary);
newBookCard();
document.getElementById("bookTitle").value = ""
document.getElementById("bookAuthor").value = ""
document.getElementById("bookPages").value = ""
}
const bookCards = document.querySelector(".all-book-cards");
bookCards.innerHTML = htmlCode;
function openForm() {
document.getElementById("myForm").style.display = "block";
}
function submitForm(){
let a = document.getElementById("bookTitle")
}
function closeForm() {
document.getElementById("myForm").style.display = "none";
}
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Library</title>
<meta charset="UTF-8"/>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id = "container" img src="images/bookShelf.jpeg">
<div id = "titleCard"> My Library</div>
<div class = "all-book-cards"></div>
<button class="open-button" onclick="openForm()">Add Book</button>
<div class="form-popup" id="myForm">
<form action="index.html" class="form-container">
<h1>Add Book</h1>
<label for="bookTitle"><b>Title:</b></label>
<input id="bookTitle" type="text" placeholder="Enter Title" name="bookTitle" required>
<label for="bookAuthor"><b>Author:</b></label>
<input id="bookAuthor" type="text" placeholder="Enter Author" name="bookAuthor" required>
<label for="bookPages"><b>Pages:</b></label>
<input id="bookPages" type="text" placeholder="Enter Pages" name="bookPages" required>
<button id="submit" type="button" class="btn">Add</button>
<button type="button" class="btn cancel" onclick="closeForm()">Close</button>
</form>
</div>
</div>
<script src ="script.js"></script>
</body>
</html>
CSS
.all-book-cards{
width: 20em;
display: flex;
flex-direction: column;
}
entry {
display: flex;
justify-content: space-between;
flex-wrap: wrap;
border: black;
border-width: 3px;
border-style: groove;
padding-left: 5px;
padding-right: 5px;
margin-bottom: 2px;
}
{box-sizing: border-box;}
.open-button {
background-color: #555;
color: white;
padding:16px 20px;
border: none;
cursor: pointer;
opacity: 0.8;
position: fixed;
bottom: 23px;
right: 28px;
width: 90px;
}
.form-popup {
display: none;
position: fixed;
bottom: 0;
right: 15px;
border: 3px solid #f1f1f1;
z-index: 9;
}
.form-container {
max-width: 300px;
padding: 10px;
background-color: white;
}
.form-container input[type=text] {
width: 100%;
padding: 15px;
margin: 5px 0 22px 0;
border: none;
background: #f1f1f1;
}
.form-container input[type=text]:focus {
background-color: rgb(161, 161, 161);
outline: none;
}
.form-container .btn {
background-color: #04AA6d;
color: white;
padding: 16px 20px;
border: none;
cursor: pointer;
width: 100%;
margin-bottom: 10px;
opacity: 0.8;
}
.form-container .cancel {
background-color: red;
}
.form-container .btn:hover, .open-button:hover {
opacity: 1;
}
/* The switch - the box around the slider */
.switch {
position: relative;
display: inline-block;
width: 60px;
height: 34px;
}
/* Hide default HTML checkbox */
.switch input {
opacity: 0;
width: 0;
height: 0;
}
/* The slider */
.slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ccc;
-webkit-transition: .4s;
transition: .4s;
}
.slider:before {
position: absolute;
content: "";
height: 26px;
width: 26px;
left: 4px;
bottom: 4px;
background-color: white;
-webkit-transition: .4s;
transition: .4s;
}
input:checked + .slider {
background-color: #2196F3;
}
input:focus + .slider {
box-shadow: 0 0 1px #2196F3;
}
input:checked + .slider:before {
-webkit-transform: translateX(26px);
-ms-transform: translateX(26px);
transform: translateX(26px);
}
/* Rounded sliders */
.slider.round {
border-radius: 34px;
}
.slider.round:before {
border-radius: 50%;
}
There is a few issues with your code, but the main reason you don't see any changes in the DOM is that you try to find an element by id "main", but no such element is defined.
So step one is putting an id on the element containing your books:
<div id="main" class="all-book-cards"></div>
Another issue is that you change the DOM in different ways on many places in your javascript code which makes it harder to figure out what's going on. You could change the addBookToLibrary to actually add elements to the DOM aswell. To ensure consistency with the initial books you create in the foor loop, I have changed the addBookToLibrary to handle the entire creation and removed the for loop.
//add object to library
function addBookToLibrary(Book){
myLibrary.push(Book);
let html = `
<entry>
<div>
<h3>Title: ${Book.title}</h3>
<h3>Author: ${Book.author}</h3>
<h3>Pages: ${Book.pages}</h3>
<label class="switch">
<input type="checkbox">
<span class="slider round"></span>
</label>
</div>
</entry>
`;
var newEl = document.createElement("template");
newEl.innerHTML = html.trim();
document.getElementById('main').appendChild(newEl.content.firstChild);
}
Below is a CodePen for the full example.
https://codepen.io/rasm586c/pen/PoKdNdd

How to display customized output based on field values

So my aim is to create a pop up modal where one could click to enter their regional school code in a text or number field to see if they are eligible for the files posted or not.
for example, if your code is 11002, you should get the recommended message else the apology message also I would like to have a button that can prompt user to go back and enter a new code if the last one is not accepted. This should all be on the same page.
Below is my code so far but I wish to display the result in a span as plain text not as in a field.
<style>
#result {
width: 100%;
}
#btn1 {
float: right;
}
</style>
<script>
function locationlookup() {
var result = document.getElementById("areacode").value;
var schooling;
if (result == 11002) {
schooling = "Great! Your school is eligible for this course";
} else if (result == 11003) {
schooling = "Great! Your school is eligible for this course";
} else if (result == 11004) {
schooling = "Your school is eligible but you need good conduct certificate";
} else {
schooling = "Sorry. we currently do not serve in your entered location";
}
document.getElementById("result").value = schooling;
}
</script>
<table align="center">
<tr>
<th>School Area code: <input type="text" name="areacode" id="areacode" >
<button onclick="locationlookup()" id="btn1">Lookup</button>
</th>
</tr>
<tr>
<th>
<input type="text" name="result" id="result" readonly></th>
<!-- I wish to change the above field to a span so no limitations. but stuff don't
work for me -->
</tr>
</table>
Maybe something like following snippet:
const input = document.querySelector("#areacode")
const span = document.querySelector("#result")
const btn = document.querySelector("#btnTryAgain")
function locationlookup() {
const result = input.value;
let schooling;
let results = [11002, 11003, 11004]
if (results.includes(Number(result))) {
schooling = "Great! Your school is eligible for this course"
} else {
schooling = "Sorry. we currently do not serve in your entered location"
btn.classList.toggle('hideBtn')
}
span.innerText = schooling;
}
function tryAgain() {
input.value = ''
span.innerText = '';
btn.classList.toggle('hideBtn')
input.focus()
}
#result {
width: 100%;
}
#btn1 {
float: right;
}
.hideBtn {
display: none;
}
<table align="center">
<tr>
<th>School Area code: <input type="text" name="areacode" id="areacode" >
<button onclick="locationlookup()" id="btn1">Lookup</button>
</th>
</tr>
<tr>
<th>
<span id="result"></span>
<button onclick="tryAgain()" id="btnTryAgain" class="hideBtn btn">Try again</button>
</th>
</tr>
</table>
So I found the below walk around to the problem which is quite handy but I will like to use that of Nikola if it finally works.
here is the code.
function openForm() {
document.getElementById("myForm").style.display = "block";
}
function closeForm() {
document.getElementById("myForm").style.display = "none";
}
function locationlookup() {
var result = document.getElementById("areacode").value;
var locality;
if (result == 11002) {
locality = "Great! Your school is eligible for this course";
} else if (result == 11003) {
locality = "Great! Your school is eligible for this course";
} else if (result == 11004) {
locality = "Your school is eligible but you need good conduct certificate and more whatever text for the coding";
} else {
locality = "Sorry. we currently do not serve in your entered location";
}
const el = document.querySelector('div[contenteditable]');
el.addEventListener('input', () => console.log(el.textContent));
el.textContent = locality;
}
/* Button used to open the contact form - fixed at the bottom of the page */
.open-button {
background-color: black;
color: white;
padding: 5px 5px;
border: none;
cursor: pointer;
opacity: 1;
}
.spanishly3 {
text-align: left;
}
.spanishly2 {
float: right;
}
.bold2 {
font-size: 16px;
}
.spanishly3:before {
content: "";
display: block;
background: url("icon.png") no-repeat;
width: 20px;
height: 20px;
float: left;
margin: 0 6px 0 0;
}
/* The popup form - hidden by default */
.form-popup {
display: none;
position: fixed;
/*bottom: 50%;*/
right: 50%;
border: 3px solid #f1f1f1;
z-index: 9;
}
/* Add styles to the form container */
.form-container {
max-width: 500px;
padding: 10px;
background-color: white;
}
/* Full-width input fields */
.form-container input[type=text], .form-container input[type=password] {
width: 100%;
padding: 15px;
margin: 5px 0 22px 0;
border: none;
background: #f1f1f1;
}
/* When the inputs get focus, do something */
.form-container input[type=text]:focus, .form-container input[type=password]:focus {
background-color: #ddd;
outline: none;
}
/* Set a style for the submit/login button */
.form-container .btn {
background-color: #04AA6D;
color: white;
padding: 16px 20px;
border: none;
cursor: pointer;
width: 100%;
margin-bottom:10px;
opacity: 0.8;
}
/* Add a red background color to the cancel button */
.form-container .cancel {
background-color: red;
}
/* Add some hover effects to buttons */
.form-container .btn:hover, .open-button:hover {
opacity: 1;
}
div[contenteditable] {
border: 1px solid black;
width: 300px;
border: none;
font-weight: bold;
}
<button class="open-button" onclick="openForm()"><div class="spanishly2"><span class="spanishly3" style="align: left;">hello</span><p><b class="bold2">Select Your Address</b></p></div></button>
<div class="form-popup" id="myForm">
<form action="/action_page.php" class="form-container">
Area code: <input type="text" name="areacode" id="areacode" placeholder="00000">
<button onclick="locationlookup()" id="btn1">Lookup</button>
<div contenteditable></div>
<p><i>or login to set/use your location</i></p>
<br>
<label for="email"><b>Email</b></label>
<input type="text" placeholder="Enter Email" name="email" required>
<label for="psw"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="psw" required>
<button type="submit" class="btn">Login</button>
<button type="button" class="btn cancel" onclick="closeForm()">Close</button>
Manage addresses
</form>
</div>

Function error: Uncaught TypeError: undefined is not a function

Made a script that checks if: $("#password") has 9 symbols and if $("#password") = $("#confirm_password").
The problem is when I try to enable the "submit" button... What is wrong with "function submitButton()"?
$("form span").hide();
$('input[type="submit"]').attr("disabled", "true");
var samePass = false;
var eight = false;
var $password01 = $("#password");
var $password02 = $("#confirm_password")
//Why this function doesn't work?
function submitButton() {
if (samePass && eight){
$('input[type="submit"]').removeAttr('disabled');
};
};
//Checks if the pass has 8 symbles
function passwordEvent() {
if ($password01.val().length > 8) {
eight = true;
$password01.next().hide().submitButton();
} else {
$password01.next().show();
};
};
//Checks if the two passwards are the same
function passwordCheck() {
if($password02.val() !== $password01.val()) {
$password02.next().show();
} else {
samePass = true;
$password02.next().hide().submitButton();
};
};
$password01.focus(passwordEvent).keyup(passwordEvent).focus(passwordCheck).keyup(passwordCheck);
$password02.focus(passwordCheck).keyup(passwordCheck);
$("form span").hide();
$('input[type="submit"]').attr("disabled", "true");
var samePass = false;
var eight = false;
var $password01 = $("#password");
var $password02 = $("#confirm_password")
//Why this function doesn't work?
function submitButton() {
if (samePass && eight){
$('input[type="submit"]').removeAttr('disabled');
};
};
//Checks if the pass has 8 symbles
function passwordEvent() {
if ($password01.val().length > 8) {
eight = true;
$password01.next().hide().submitButton();
} else {
$password01.next().show();
};
};
//Checks if the two passwards are the same
function passwordCheck() {
if($password02.val() !== $password01.val()) {
$password02.next().show();
} else {
samePass = true;
$password02.next().hide().submitButton();
};
};
$password01.focus(passwordEvent).keyup(passwordEvent).focus(passwordCheck).keyup(passwordCheck);
$password02.focus(passwordCheck).keyup(passwordCheck);
body {
background: #384047;
font-family: sans-serif;
font-size: 10px
}
form {
background: #fff;
border-radius: 10px;
padding: 4em 4em 2em;
box-shadow: 0 0 1em #222;
max-width: 400px;
margin: 100px auto;
}
p {
margin: 0 0 3em 0;
position: relative;
}
label {
font-size: 1.6em;
font-weight:600;
color: #333;
display: block;
margin: 0 0 .5em;
}
input {
display: block;
height: 40px;
width: 100%;
box-sizing: border-box;
outline: none
}
input[type="text"],
input[type="password"] {
background: #f5f5f5;
border: 1px solid #F0F0F0;
border-radius: 5px;
font-size: 1.6em;
padding: 1em 0.5em;
}
input[type="text"]:focus,
input[type="password"]:focus {
background: #fff
}
span {
border-radius: 5px;
padding: 7px 10px;
background: #2F558E;
color: #fff;
width: 160px;
display: block; /* Needed for the width to work */
text-align: center; /* For the inner text */
position: absolute;
left: 105%;
top: 25px;
}
span:after {
content: " ";
position: absolute;
/* pointer-events: none;*/
right: 100%;
top: 50%;
/*
height: 0;
width: 0;
*/
border: solid transparent;
/* border-color: rgba(136, 183, 213, 0);*/
border-right-color: #2F558E;
border-width: 8px;
margin-top: -8px;
}
.enableSub {
background: #0099FF;
border: none;
border-radius: 5px;
color: white;
height: 50px;
box-shadow: 0 3px 0 0 #005C99;
}
.disableSub {
background: #AEAEAE;
border: none;
border-radius: 5px;
color: white;
height: 50px;
}
<!DOCTYPE html>
<html>
<head>
<title>Sign Up Form</title>
<link rel="stylesheet" href="css/style.css" type="text/css" media="screen" title="no title" charset="utf-8">
</head>
<body>
<form action="#" method="post">
<p>
<label for="username">Username</label>
<input id="username" name="username" type="text">
</p>
<p>
<label for="password">Password</label>
<input id="password" name="password" type="password">
<span>Enter a password longer than 8 characters</span>
</p>
<p>
<label for="confirm_password">Confirm Password</label>
<input id="confirm_password" name="confirm_password" type="password">
<span>Please confirm your password</span>
</p>
<p>
<input type="submit" class="disableSub" value="SUBMIT">
</p>
</form>
<script src="http://code.jquery.com/jquery-1.11.0.min.js" type="text/javascript" charset="utf-8"></script>
<script src="js/app.js" type="text/javascript" charset="utf-8"></script>
</body>
</html>
$password01.next().hide().submitButton();
et al. won't work. You instead need to do;
$password01.next().hide();
submitButton();
You've declared submitButton as a function, not a method on a jQuery object, hence you need to call it as such.
The "undefined is not a function" error appears cryptic at first, but becomes clear once understood.
Since the jQuery object returned from hide() doesn't have a submitButton property (or method), hide().submitButton returns undefined. You're then trying to call that as a function (with the ()), hence JavaScript is telling you that undefined is not a function.
As well as the above, your logic is also flawed. Namely samePass is being set to true the second you click into the password1 field (since, on focus, when they're both blank, $password02.val() === $password01.val()). That means that as soon as password is > 8 chars, both conditions will match, and your submit will be enabled.
To fix this, you should probably be setting samePass and eight to false when they don't match their criteria, and calling submitButton() in all cases to update the state
//Why this function doesn't work?
function submitButton() {
if (samePass && eight) {
$('input[type="submit"]').removeAttr('disabled');
} else {
$('input[type="submit"]').attr('disabled', "true");
}
};
//Checks if the pass has 8 symbles
function passwordEvent() {
if ($password01.val().length > 8) {
eight = true;
$password01.next().hide();
submitButton();
} else {
eight = false;
$password01.next().show();
submitButton();
};
};
//Checks if the two passwards are the same
function passwordCheck() {
if ($password02.val() !== $password01.val()) {
samePass = false;
$password02.next().show();
submitButton();
} else {
samePass = true;
$password02.next().hide();
submitButton();
};
};
... which then works; http://jsfiddle.net/9qqnqLxm/

Categories