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>
Related
I have been trying to get a plus minus button integrated into my number input. I have been able to update the field between the buttons with the new value however am trying to get that value to populate a second area (specifically a button) If I select the number input and click up or down arrows both the input and the button text are successfully updating, I am just stuck on mingling the two together.
How do I get the button to load the value of the number field after clicking the plus and minus buttons?
var adultModal = document.getElementById("adultModal");
var adultBtn = document.getElementById("guests");
var adultSpan = document.getElementsByClassName("adultClose")[0];
adultBtn.onclick = function() {
adultModal.style.display = "block";
}
adultSpan.onclick = function() {
adultModal.style.display = "none";
}
window.onclick = function(event) {
if (event.target == adultModal) {
adultModal.style.display = "none";
}
}
// NUMBER FIELD PLUS / MINUS SCRIPT
function incrementValue(e) {
e.preventDefault();
var fieldName = $(e.target).data('field');
var parent = $(e.target).closest('div');
var currentVal = parseInt(parent.find('input[name=' + fieldName + ']').val(), 10);
if (!isNaN(currentVal)) {
parent.find('input[name=' + fieldName + ']').val(currentVal + 1);
} else {
parent.find('input[name=' + fieldName + ']').val(0);
}
}
function decrementValue(e) {
e.preventDefault();
var fieldName = $(e.target).data('field');
var parent = $(e.target).closest('div');
var currentVal = parseInt(parent.find('input[name=' + fieldName + ']').val(), 10);
if (!isNaN(currentVal) && currentVal > 0) {
parent.find('input[name=' + fieldName + ']').val(currentVal - 1);
} else {
parent.find('input[name=' + fieldName + ']').val(0);
}
}
$('.input-group').on('click', '.button-plus', function(e) {
incrementValue(e);
});
$('.input-group').on('click', '.button-minus', function(e) {
decrementValue(e);
});
function updateGuests() {
let adultNumb = document.getElementById("adultQuantity");
let produceAdult = document.getElementById('adultValue');
produceAdult.innerHTML = adultNumb.value;
let childNumb = document.getElementById("childQuantity");
let produceChild = document.getElementById('childValue');
produceChild.innerHTML = childNumb.value;
}
/* The Modal (background) */
.modal {
display: none;
/* Hidden by default */
position: fixed;
/* Stay in place */
z-index: 1;
/* Sit on top */
padding-top: 100px;
/* Location of the box */
left: 0;
top: 0;
width: 100%;
/* Full width */
height: 100%;
/* Full height */
overflow: auto;
/* Enable scroll if needed */
}
/* Modal Content */
.modal-content {
background-color: #fefefe;
margin: auto;
padding: 5px 20px;
border: 1px solid #888;
width: 280px;
position: relative;
}
/* The Close Button */
.adultClose,
.childClose {
color: #aaaaaa;
position: absolute;
right: 5px;
top: 0px;
font-size: 22px;
font-weight: bold;
cursor: pointer;
}
.close:hover,
.close:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
/* INPUT NUMBER PLUS/MINUS BUTTONS */
input,
textarea {
border: 1px solid #eeeeee;
box-sizing: border-box;
margin: 0;
outline: none;
padding: 10px;
}
input[type="button"] {
-webkit-appearance: button;
cursor: pointer;
}
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
-webkit-appearance: none;
}
.input-group {
clear: both;
margin: 15px 0;
position: relative;
}
.input-group input[type='button'] {
background-color: #eeeeee;
min-width: 38px;
width: auto;
transition: all 300ms ease;
}
.input-group .button-minus,
.input-group .button-plus {
font-weight: bold;
height: 38px;
padding: 0;
width: 38px;
position: relative;
}
.input-group .quantity-field {
position: relative;
height: 38px;
left: -6px;
text-align: center;
width: 62px;
display: inline-block;
font-size: 13px;
margin: 0 0 5px;
resize: vertical;
}
.button-plus {
left: -13px;
}
input[type="number"] {
-moz-appearance: textfield;
-webkit-appearance: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3>Guests</h3>
<button id="guests" type="button" class="adults">
<span class="bw-toggle__value"><span id="adultValue">2</span> Adults <span class="bw-divide">/</span> <span id="childValue">0</span> Children</span>
</button>
<!-- Adult Modal -->
<div id="adultModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="adultClose">×</span>
<div class="input-group">
ADULTS
<input type="button" value="-" class="button-minus" data-field="quantity">
<input type="number" step="1" max="" value="2" name="quantity" class="quantity-field" id="adultQuantity" onchange="updateGuests()">
<input type="button" value="+" class="button-plus" data-field="quantity">
</div>
<div class="input-group">
CHILDREN
<input type="button" value="-" class="button-minus" data-field="quantity">
<input type="number" step="1" max="" value="0" name="quantity" class="quantity-field" id="childQuantity" onchange="updateGuests()">
<input type="button" value="+" class="button-plus" data-field="quantity">
</div>
</div>
</div>
Just call updateGuests() in your increment and decrement functions. You were 99% there.
I'd encourage you to move away from jQuery. You're halfway there with this code anyway, and it's a crutch against robust learning of JavaScript. These operations are simple enough that you just don't need it. See https://youmightnotneedjquery.com.
var adultModal = document.getElementById("adultModal");
var adultBtn = document.getElementById("guests");
var adultSpan = document.getElementsByClassName("adultClose")[0];
adultBtn.onclick = function() {
adultModal.style.display = "block";
}
adultSpan.onclick = function() {
adultModal.style.display = "none";
}
window.onclick = function(event) {
if (event.target == adultModal) {
adultModal.style.display = "none";
}
}
// NUMBER FIELD PLUS / MINUS SCRIPT
function incrementValue(e) {
e.preventDefault();
var fieldName = $(e.target).data('field');
var parent = $(e.target).closest('div');
var currentVal = parseInt(parent.find('input[name=' + fieldName + ']').val(), 10);
if (!isNaN(currentVal)) {
parent.find('input[name=' + fieldName + ']').val(currentVal + 1);
} else {
parent.find('input[name=' + fieldName + ']').val(0);
}
updateGuests();
}
function decrementValue(e) {
e.preventDefault();
var fieldName = $(e.target).data('field');
var parent = $(e.target).closest('div');
var currentVal = parseInt(parent.find('input[name=' + fieldName + ']').val(), 10);
if (!isNaN(currentVal) && currentVal > 0) {
parent.find('input[name=' + fieldName + ']').val(currentVal - 1);
} else {
parent.find('input[name=' + fieldName + ']').val(0);
}
updateGuests();
}
$('.input-group').on('click', '.button-plus', function(e) {
incrementValue(e);
});
$('.input-group').on('click', '.button-minus', function(e) {
decrementValue(e);
});
function updateGuests() {
let adultNumb = document.getElementById("adultQuantity");
let produceAdult = document.getElementById('adultValue');
produceAdult.innerHTML = adultNumb.value;
let childNumb = document.getElementById("childQuantity");
let produceChild = document.getElementById('childValue');
produceChild.innerHTML = childNumb.value;
}
/* The Modal (background) */
.modal {
display: none;
/* Hidden by default */
position: fixed;
/* Stay in place */
z-index: 1;
/* Sit on top */
padding-top: 100px;
/* Location of the box */
left: 0;
top: 0;
width: 100%;
/* Full width */
height: 100%;
/* Full height */
overflow: auto;
/* Enable scroll if needed */
}
/* Modal Content */
.modal-content {
background-color: #fefefe;
margin: auto;
padding: 5px 20px;
border: 1px solid #888;
width: 280px;
position: relative;
}
/* The Close Button */
.adultClose,
.childClose {
color: #aaaaaa;
position: absolute;
right: 5px;
top: 0px;
font-size: 22px;
font-weight: bold;
cursor: pointer;
}
.close:hover,
.close:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
/* INPUT NUMBER PLUS/MINUS BUTTONS */
input,
textarea {
border: 1px solid #eeeeee;
box-sizing: border-box;
margin: 0;
outline: none;
padding: 10px;
}
input[type="button"] {
-webkit-appearance: button;
cursor: pointer;
}
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
-webkit-appearance: none;
}
.input-group {
clear: both;
margin: 15px 0;
position: relative;
}
.input-group input[type='button'] {
background-color: #eeeeee;
min-width: 38px;
width: auto;
transition: all 300ms ease;
}
.input-group .button-minus,
.input-group .button-plus {
font-weight: bold;
height: 38px;
padding: 0;
width: 38px;
position: relative;
}
.input-group .quantity-field {
position: relative;
height: 38px;
left: -6px;
text-align: center;
width: 62px;
display: inline-block;
font-size: 13px;
margin: 0 0 5px;
resize: vertical;
}
.button-plus {
left: -13px;
}
input[type="number"] {
-moz-appearance: textfield;
-webkit-appearance: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3>Guests</h3>
<button id="guests" type="button" class="adults">
<span class="bw-toggle__value"><span id="adultValue">2</span> Adults <span class="bw-divide">/</span> <span id="childValue">0</span> Children</span>
</button>
<!-- Adult Modal -->
<div id="adultModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="adultClose">×</span>
<div class="input-group">
ADULTS
<input type="button" value="-" class="button-minus" data-field="quantity">
<input type="number" step="1" max="" value="2" name="quantity" class="quantity-field" id="adultQuantity" onchange="updateGuests()">
<input type="button" value="+" class="button-plus" data-field="quantity">
</div>
<div class="input-group">
CHILDREN
<input type="button" value="-" class="button-minus" data-field="quantity">
<input type="number" step="1" max="" value="0" name="quantity" class="quantity-field" id="childQuantity" onchange="updateGuests()">
<input type="button" value="+" class="button-plus" data-field="quantity">
</div>
</div>
</div>
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
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);
}
I have created a contact form that will appear when a button is clicked. This works fine. However, when I add js-code to close the contact via a button inside the contact form it won't open at all.
I think it's a problem with the logic, but I can't locate where. Syntax seems fine.
Be aware that the js code which renders everything useless has been commented out. I have added it in the descriptions, so it should hopefully be clear for anyone to make head and tales out of it. Also, you must click on the window to make the contact form appear because the display in css is set to 'none' and changes upon clicking to 'flex'.
//this function will make the contact-form open upon clicking the "get a quote" Button
window.addEventListener('click', function() {
let quoteButton = document.getElementById('quote-button');
let contactWrapper = document.getElementById('contact-wrapper');
if (contactWrapper.style.display == 'none') {
contactWrapper.style.display = 'flex';
} else {
(contactWrapper.style.display = 'none');
}
});
//this function shoud make the contact-form disappear upon clicking the "Back" Button, however above code (to make contact form appear) does not work if bellow code is enabled.
/*
window.addEventListener('click', function() {
let backbutton = document.getElementById('back-button');
let contactWrapper = document.getElementById('contact-wrapper');
if (contactWrapper.style.display == 'flex') {
contactWrapper.style.display = 'none';
}
});
*/
//this function will make the contact-form stick in place when opened
window.addEventListener('scroll', function() {
let contactForm = document.getElementById('contact-wrapper');
let maxTopYPosition = 0;
let maxBottomYPosition = 4000;
if (window.pageYOffset >= maxTopYPosition && window.pageYOffset < maxBottomYPosition) {
contactForm.classList.add('sticky-contact-wrapper');
} else {
contactForm.classList.remove('sticky-contact-wrapper');
}
});
/* Beginning of Contact-Form
The contact form is only visible on click*/
#contact-wrapper {
display: none;
left: 5%;
z-index: 10000;
font-family: Arial, Helvetica, sans-serif;
background-image: linear-gradient(to bottom right, rgba(122, 122, 122, 0.975), rgba(173, 173, 173, 0.975), rgba(235, 235, 235, 0.975), rgba(201, 201, 201, 0.975), rgba(122, 122, 122, 0.975));
width: 90%;
margin: 5vh auto;
padding: 1vh 1vw;
flex-direction: row;
flex-wrap: wrap;
border: 5px solid black;
border-radius: 10px;
box-shadow: 10px 10px rgb(206, 197, 197, 0.5);
}
.sticky-contact-wrapper {
position: absolute;
position: fixed;
top: 10vh;
opacity: 1;
animation-name: fadeInOpacity;
animation-iteration-count: 1;
animation-timing-function: ease-in;
animation-duration: 0.5s;
}
#keyframes fadeInOpacity {
0% {
opacity: 0;
}
100% {
opacity: 1;
}
}
.flex-item {
padding: 2vh 2vw;
}
.flex-item1 {
flex-grow: 7;
}
.flex-item2 {
flex-grow: 3;
display: flex;
}
#contact-form p {
line-height: 0;
margin: 2vh 0 6px 0;
font-size: 16px;
}
#contact-form .input-field {
height: 5vh;
width: 80%;
}
#contact-form .message-field{
height: 12vh;
}
.button-flex-wrapper {
display: flex;
flex-direction: row;
width: 80%;
justify-content: space-between;
}
#contact-form button {
display: block;
height: 5vh;
width: 10vw;
min-width: 75px;
color: white;
background: rgb(173, 66, 66);
border: none;
border-radius: 5px;
text-transform: uppercase;
}
.dropZone {
width: 33vw;
height: 75%;
margin: auto;
border: 2px dashed #ccc;
line-height: -50%;
text-align: center;
display: table;
}
.dropZone h3 {
display: table-cell;
text-align: center;
vertical-align: middle;
background: rgb(235, 231, 231);
height: 200px; width:200px;
color: black;
}
.dropZone.dragover {
border-color: black;
color: #000;
}
/* End of contact form */
<!-- CONTACT-FORM -->
<div id="contact-wrapper">
<div class="flex-item flex-item1">
<form id="contact-form" action="" method="POST"
enctype="multipart/form-data">
<p>Name</p>
<input class="input-field" type="text" placeholder="name">
<p>Last Name</p>
<input class="input-field" type="text" placeholder="name">
<p>work email</p>
<input class="input-field" type="text" placeholder="email">
<p>phone</p>
<input class="input-field" type="text" placeholder="phone">
<p>message</p>
<input class="input-field message-field" type="text">
<br><br>
<p>Submit your request</p>
<br>
<div class="button-flex-wrapper">
<div>
<button id="back-button" type="button">Back</button>
</div>
<div>
<button id="submit-button" type="button">Submit</button>
</div>
</div>
</div>
<div id="uploads" class="flex-item flex-item2">
<div class="dropZone" id="dropZone">
<h3>Drop Files Here</h3>
</div>
</div>
</div>
As pointed out, the problem was that the event handler was listening for any kind of click event in the window object. Instead I refactored the code and put the respective buttons in variables and added the addEventListener.
// contact-form opens upon clicking the "get a quote" Button
let quoteButton = document.getElementById('quote-button');
quoteButton.addEventListener('click', function() {
let contactWrapper = document.getElementById('contact-wrapper');
if (contactWrapper.style.display == 'none') {
contactWrapper.style.display = 'flex';
} else {
(contactWrapper.style.display = 'none');
}
});
//contact-form disapears when clicking "back" Button
let backbutton = document.getElementById('back-button');
backbutton.addEventListener('click', function() {
let contactWrapper = document.getElementById('contact-wrapper');
if (contactWrapper.style.display == 'flex') {
contactWrapper.style.display = 'none';
}
});
Your JS is just listening for any 'click' right now, that seems to be the problem. You should add an onclick handler to your button via your html and have that perform the JS function.
<button onclick="openContactForm()" id="quote-button">Open Contact</button>
I turned your code into a codepen so you and others can check it out and provide some additional input. I also made the changes I spoke about in it for you.
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/