I'm doing a Contact form and when I'm using the error messages when the infos aren't correct it works but I can't remove the messages once it's corrected.
What's wrong/missing in my code please?
Here's my code :
// Get Data
const nom = document.querySelector("#nom");
const prenom = document.querySelector("#prenom");
const email = document.querySelector("#email");
const message = document.querySelector("#message");
const success = document.querySelector("#success");
const errorNodes = document.querySelectorAll(".error");
// Validate Data
clearMessages ();
let errorFlag = false;
function validateForm(){
errorNodes[0].innerText = "";
errorNodes[1].innerText = "";
if(nom.value.length < 1){
errorNodes[0].innerText = "Le nom ne peut pas être vide.";
errorFlag = true;
}
if(prenom.value.length < 1){
errorNodes[1].innerText = "Le prénom ne peut pas être vide.";
errorFlag = true;
}
if(!errorFlag){
success.innerText = "Message envoyé!";
}
}
// Clear error / success messages
function clearMessages(){
for (let i = 0; i < errorNodes.length; i++){
errorNodes[i].innerText = "";
}
success.innerText = "";
}
// Check if email is valid
function emailIsValid(email){
let pattern = /\S+#\S+\.\S+/;
return pattern.test(email);
}
* {
font-family: Arial;
font-size: 16px;
}
body {
background: #5a8cdb;
}
form {
max-width: 550px;
width: 90%;
background: white;
margin: 90px auto 0 auto;
padding: 40px;
border-radius: 10px;
box-sizing: border-box;
}
h1 {
font-size: 32px;
margin: 0;
text-align: center;
}
.item label {
display: block;
margin: 20px 0;
}
.item input, textarea {
width: 100%;
padding: 10px;
box-sizing: border-box;
outline: none;
resize: none;
border: none;
border-bottom: 1px solid #d3d3d3;
}
input[type="text"]:focus, textarea:focus {
border-bottom: 1px solid #5a8cdb;
}
textarea::-webkit-scrollbar {
width: 3px;
}
textarea::-webkit-scrollbar-thumb {
background-color: #5a8cdb;
}
.center {
text-align: center;
}
input[type="submit"] {
margin-top: 30px;
width: 90%;
max-width: 200px;
border-radius: 5px;
background: #5a8cdb;
color: white;
font-size: 16px;
cursor: pointer;
}
input[type="submit"]:hover {
background: #3F73C5;
}
.error {
display: block;
margin: 5px 0;
color: red;
}
.error-border {
border-bottom: 1px solid red;
}
#success {
color: green;
}
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Formulaire de Contact</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<form onsubmit="event.preventDefault(); validateForm()">
<h1>Contactez-nous</h1><br>
<div class="item">
<label for="nom">Nom</label>
<input type="text" id="nom" placeholder="Votre nom">
<small class="error"></small>
<label for="prenom">Prénom</label>
<input type="text" id="prenom" placeholder="Votre prénom">
<small class="error"></small>
<div class="center">
<input type="submit" value="Envoyez">
<p id="success"></p>
</div>
</form>
<script src="script.js"></script>
</body>
</html>
..........................................................................
.........................................................................
well you have to call 'clearMessages()' after editing input somehow. or during editing.
add this to js file:
nom.addEventListener('change', clearMessages);
prenom.addEventListener('change', clearMessages);
nom.addEventListener('focus', clearMessages);
prenom.addEventListener('focus', clearMessages);
EDIT :
change code in clear message to :
errorFlag = false;
for (let i = 0; i < errorNodes.length; i++){
errorNodes[i].innerText = "";
}
success.innerText = "";
and also edit this :
let errorFlag = false;
clearMessages ();
You don't have necessary code when everything is correct within validateForm method. So either add statement that if everything is okay, will remove the the error messages with innerHTML = '' or instead of calling the validation on formSubmit you can:
nom.addEventListener('keyup', (e) => {
if(e.target.value < 1)
//show error code
else //remove error
})
This can be added to every input you want to validate.
When you call the validateForm(), clear them before it does anything else
function validateForm(){
errorNodes[0].innerText = "";
errorNodes[1].innerText = "";
Then the rest of your code and add this
if(!errorFlag){
errorNodes[0].innerText = "";
errorNodes[1].innerText = "";
success.innerText = "Message envoyé!";
}
Easiest way
It is because the code didn't call the 'clearMessages()' after checking the form is validated.
Move the 'clearMessages()' insdie the 'if(!errorFlag)' condition block so the function will call 'clearMessages()' once the form is submit with no error.
if(!errorFlag){
success.innerText = "Message envoyé!";
clearMessages ();
}
Related
I've been working on a contact form with validation. Im using constraint validation api, and I have these files which kinda works the way I want, but I wonder if there's a way I can make the errorboxes red when there's an error, and white (or hidden) when there's no validation error. There's probably some code which is unneccesary, and I plan to clean it up when i'm satisfied with the functionality, but now it looks like i have errors everywhere when everything is valid.
const form = document.getElementsByTagName('form')[0];
const email = document.getElementById('mail');
const emailError = document.querySelector('#mail + span.error');
const navn = document.getElementById('navn');
const navnError = document.querySelector('#navn + span.error');
const telefon = document.getElementById('telefon');
const telefonError = document.querySelector('#telefon + span.error')
const message = document.getElementById('message');
const messageError = document.querySelector('#message + span.error')
const personvern = document.getElementById('personvern');
const personvernError = document.querySelector('#personvern + span.error')
// THIS DIV WILL CONTAIN ERROR MESSAGES
const errOutput = document.querySelector('.errorsOutput')
email.addEventListener('input', function(event) {
if (email.validity.valid) {
emailError.innerHTML = '';
emailError.className = 'error';
} else {
showError();
}
});
navn.addEventListener('input', function(event) {
if (navn.validity.valid) {
navnError.innerHTML = '';
navnError.className = 'error';
} else {
showError();
}
})
telefon.addEventListener('input', function(event) {
if (telefon.validity.valid) {
telefonError.innerHTML = '';
telefonError.className = 'error';
} else {
showError();
}
})
message.addEventListener('input', function(event) {
if (message.validity.valid) {
messageError.innerHTML = '';
messageError.className = 'error';
} else {
showError();
}
})
form.addEventListener('submit', function(event) {
if (!email.validity.valid || !navn.validity.valid || !telefon.validity.valid || !message.validity.valid) {
showError();
event.preventDefault();
}
});
function showError() {
// EMPTY ERRORS DIV
errOutput.innerHTML = ''
if (navn.validity.valueMissing) {
navnError.textContent = '* Du må fylle inn navnet ditt';
} else if (navn.validity.tooShort) {
navnError.textContect = '* Du må fylle inn hele navnet ditt'
}
// OUTPUT ERRORS IN DIV
if (navnError.textContent != '') {
errOutput.innerHTML += '<p>Navn error!</p>'
}
if (email.validity.valueMissing) {
emailError.textContent = '* Vennligst fyll inn e-posten din';
} else if (email.validity.typeMismatch) {
emailError.textContent = '* Dette er ikke en gyldig e-postadresse.';
} else if (email.validity.tooShort) {
emailError.textContent = `* Email should be at least ${ email.minLength } characters; you entered ${ email.value.length }.`;
}
// OUTPUT ERRORS IN DIV
if (emailError.textContent != '') {
errOutput.innerHTML += '<p>Email error!</p>'
}
if (telefon.validity.valueMissing) {
telefonError.textContent = '* Du må fylle inn telefonnummeret ditt'
} else if (telefon.validity.tooShort) {
telefonError.textContent = '* Du mangler ett eller flere tall. Vennligst dobbeltsjekk.'
}
// OUTPUT ERRORS IN DIV
if (telefonError.textContent != '') {
errOutput.innerHTML += '<p>Telefonnummer error!</p>'
}
if (message.validity.valueMissing) {
messageError.textContent = '* Beskjeden mangler, vennligst fyll inn'
} else if (message.validity.tooShort) {
messageError.textContent = `* Beskjed må være minst ${ message.minLength } tegn.`;
}
// OUTPUT ERRORS IN DIV
if (messageError.textContent != '') {
errOutput.innerHTML += '<p>Beskjed error!</p>'
}
}
// Set the styling appropriately
emailError.className = 'error active';
navnError.className = 'error active';
telefonError.className = 'error active';
messageError.className = 'error active';
personvernError.className = 'error active';
body {
width: 600px;
padding: 0;
margin: 0 auto;
font-family: 'Open Sans', sans-serif;
font-weight: 400;
font-size: 1.1rem;
}
p * {
display: block;
}
input[type=text] {
-webkit-appearance: none;
appearance: none;
min-width: 500px;
width: 100% !important;
padding: 15px;
border: 1px solid #333;
margin: 0;
font-family: inherit;
font-size: 90%;
box-sizing: border-box;
}
input[type=email] {
-webkit-appearance: none;
appearance: none;
min-width: 500px;
width: 100% !important;
padding: 15px;
border: 1px solid #333;
margin: 0;
font-family: inherit;
font-size: 90%;
box-sizing: border-box;
}
input[type=tel] {
-webkit-appearance: none;
appearance: none;
min-width: 500px;
width: 100% !important;
padding: 15px;
border: 1px solid #333;
margin: 0;
font-family: inherit;
font-size: 90%;
box-sizing: border-box;
}
/* This is our style for the invalid fields */
input:invalid {
border-color: #900;
background-color: #FDD;
}
input:focus:invalid {
outline: none;
}
/* This is the style of our error messages */
.error {
width: 100%;
padding: 15px;
min-height: 20px;
font-size: 100%;
color: white;
background-color: #900;
display: flex;
justify-content: flex-start;
margin: 1rem 0;
}
.error.active {
padding: 0;
}
.errorsOutput {
background-color: #ac0606;
color: white;
margin: 0 0 5px 0;
}
.errorsOutput p {
padding: 1px;
}
<!DOCTYPE html>
<html>
<head>
<script src="jquery-3.6.0.min.js"></script>
<script src="kontaktskjema.js"></script>
<link rel="stylesheet" href="kontakt.css">
<meta charset="utf-8">
<title>Kontaktskjema</title>
</head>
<body>
<!-- THIS DIV WILL CONTAIN ERROR MESSAGES -->
<div class="errorsOutput">
</div>
<div class="kontaktskjema">
<div class="error">
<form novalidate>
<p>
<label for="navn">
<span>Navn:</span>
<input type="text" id="navn" name="navn" required minlength="3">
<span class="error" aria-live="polite"></span>
</label>
</p>
</div>
<div class="error">
<form novalidate>
<p>
<label for="name">
<span>Telefonnummer:</span>
<input type="tel" id="telefon" name="telefon" required minlength="8" required maxlength="8">
<span class="error" aria-live="polite"></span>
</label>
</p>
</div>
<div class="error">
<form novalidate>
<p>
<label for="mail">
<span>E-post:</span>
<input type="email" id="mail" name="mail" required minlength="6">
<span class="error" aria-live="polite"></span>
</label>
</p>
</div>
<div class="error">
<form novalidate>
<p>
<label for="message">
<span>Beskjed:</span>
<input type="text" id="message" name="message" required minlength="10">
<span class="error" aria-live="polite"></span>
</label>
</p>
</div>
<form>
<p>
<label for="personvern">
<div class="personvern">
<span>Personvern:</span>
<br>
<input type="checkbox" id="personvern" name="personvern" required>
<span>Jeg har lest og godkjent Personvernserklæringen</span>
<span class="error" aria-live="polite"></span>
</div>
</label>
</p>
<button>Send</button>
</form>
</div>
<script src="kontakt.js"></script>
</body>
</html>
Thanks!
The way I'd do it, is through application-defined element attributes.
CSS totally support attribute selectors. If you set some attribute of the div element to a certain value, say data-validation-error=true, then in your CSS
div[data-validation-error="true"] {
/* red */
}
div[data-validation-error="ok"] {
display: none; /* hidden */
}
and in JavaScript, use the setAttribute function on the div you want to control.
Notice I used the data- prefix. This is the standard HTML attribute prefix for user/application-defined attributes.
I started a beginners project to learn more about JS with a multiuser ATM.
Things I'm trying to do:
3 Users that have password and balance when they log in
The login page should redirect you to the ATM site, and it will show you your balance in a pre-built calculator
I want to make the ATM work too but I first need to get the login right
Here is my code
// Login: Try limit, page change, usernames
let entryCount = 1;
let entryLimit = 3;
let users = [
{ name: "Emilio", password: "a", balance: 1000 },
{ name: "Andrea", password: "b", balance: 20000 },
{ name: "Hugo", password: "c", balance: 300000 },
];
let mainScreen = document.getElementById('login-page')
let conctentAccountScreen = document.createTextNode("account screen")
let accountScreen = document.createElement("span").setAttribute("id", "accountScreen")
// Login
let button = document.getElementById ('login');
button.onclick = function() {
let username = document.getElementById('user').value;
let password = document.getElementById('pass').value;
userExists = false
correctPassword = false
saldoExists = false
for (let i = 0; i < users.length; i++) {
if (username == users[i].username && password == users[i].password) {
userExists = true
correctPassword = true
saldoExists = true
window.location.href = "atm.html"
} else{
alert('Try again bro')
}
if (entryCount < entryLimit) {
entryCount++
alert('Username or Password are incorrect, please try again')
} else {
alert('You exceeded the number of tries')
window.location.href = "index.html"
}
}
}
#import url(https://fonts.googleapis.com/css?family=Roboto:300);
.login-page {
width: 360px;
padding: 8% 0 0;
margin: auto;
}
.form {
position: relative;
z-index: 1;
background: #FFFFFF;
max-width: 360px;
margin: 0 auto 100px;
padding: 45px;
text-align: center;
box-shadow: 0 0 20px 0 rgba(0, 0, 0, 0.2), 0 5px 5px 0 rgba(0, 0, 0, 0.24);
}
.form input {
font-family: "Roboto", sans-serif;
outline: 0;
background: #f2f2f2;
width: 100%;
border: 0;
margin: 0 0 15px;
padding: 15px;
box-sizing: border-box;font-size: 14px;
}
h1 {
font-family: "Roboto", sans-serif;
width: 100%;
border: 0;
box-sizing: border-box;font-size: 25px;
margin-bottom: 50px;
}
.form button {
font-family: "Roboto", sans-serif;
text-transform: uppercase;
outline: 0;
background: #fce205;
width: 100%;
border: 0;
padding: 15px;
color: #FFFFFF;
font-size: 14px;
-webkit-transition: all 0.3 ease;
transition: all 0.3 ease;
cursor: pointer;
}
.form button:hover,.form button:active,.form button:focus {
background: #ffbf00;
}
.form .message {
margin: 15px 0 0;
color: #b3b3b3;
font-size: 12px;
}
.form .message a {
color: #4CAF50;
text-decoration: none;
}
.form .register-form {
display: none;
}
.container {
position: relative;
z-index: 1;
max-width: 300px;
margin: 0 auto;
}
.container:before, .container:after {
content: "";
display: block;
clear: both;
}
.container .info {
margin: 50px auto;
text-align: center;
}
.container .info h1 {
margin: 0 0 15px;
padding: 0;
font-size: 36px;
font-weight: 300;color: #1a1a1a;
.container .info span {
color: #4d4d4d;
font-size: 12px;
}
.container .info span a {
color: #000000;
text-decoration: none;
}
.container .info span .fa {
color: #EF3B3A;
}
<!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">
<!-- CSS with Bootstrap -->
<link rel="stylesheet" href="css/style.css">
<script src="js/index.js"></script>
<title>ATM</title>
</head>
<body>
<div class="login-page">
<div class="form">
<h1>Welcome back to your bank, please log in.</h1>
<form class="login-form">
<input type="text" placeholder="username" id="user">
<input type="password" placeholder="password" id="pass">
<button id="login" type="button">login</button>
</form>
</div>
</div>
<!-- JAVASCRIPT -->
</body>
</html>
Dunno if this is what you need, but to change the html page via Javascript you can simply do:
location.href = '/something.html';
Or to an external site like this:
location.href = "https://stackoverflow.com/";
Also your code will alert repeatedly as you are doing alert('Try again bro') for EVERY user in the users array... also where is userExists, correctPassword and saldoExists being declarated?
Now this seems a better way of handling if user and password exists, dunno if it's what you're trying tho:
button.onclick = function() {
let username = document.getElementById('user').value;
let password = document.getElementById('pass').value;
const user = user.find(x => username == x.username && password == x.password);
if (user) {
// Do whataver you want if user is found.
location.href = "atm.html"
} else {
// Do whataver you want if user is NOT found.
alert('Try again bro');
}
}
And as so for last observation, you might like to import your Javascript file at the end of the body in the html (more information about why here: https://hackinbits.com/interview-questions/html/why-script-tags-should-be-placed-at-the-end-of-body-tag) (this is also potentially causing the error you commented)
So I'm making a calculator in JavaScript as a way to learn JavaScript. I'd like to add some sort of Object Orientated into the project.
My HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>The Unconventional Calculator</title>
<link
href="https://fonts.googleapis.com/css?family=Roboto:400,700&display=swap"
rel="stylesheet"
/>
<link rel="stylesheet" href="assets/styles/app.css" />
</head>
<body>
<header>
<h1>The Unconventional Calculator</h1>
</header>
<section id="calculator">
<input type="number" id="input-number" />
<div id="calc-actions">
<button type="button" id="btn-add">+</button>
<button type="button" id="btn-subtract">-</button>
<button type="button" id="btn-multiply">*</button>
<button type="button" id="btn-divide">/</button>
<button type="button" id="btn-equals">=</button>
</div>
</section>
<section id="results">
<h2 id="current-calculation">0</h2>
<h2>Result: <span id="current-result">0</span></h2>
</section>
<section class="credit">
<h1>Check out my code on GitHub
<br>Type your number, press enter, repeat until you're done and then press enter.</h1>
</section>
<!-- So the site loads first then the js runs -->
<script src="assets/scripts/vendor.js"></script>
<script src="assets/scripts/app.js"> </script>
</body>
</html>
MY CSS
* {
box-sizing: border-box;
}
html {
font-family: 'Roboto', open-sans;
}
body {
margin: 0;
}
header {
background: #6d0026;
color: white;
padding: 1rem;
text-align: center;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.26);
width: 100%;
}
#results,
#calculator {
margin: 2rem auto;
width: 40rem;
max-width: 90%;
border: 1px solid #6d0026;
border-radius: 10px;
padding: 1rem;
color: #6d0026;
}
#results {
text-align: center;
}
#calculator input {
font: inherit;
font-size: 3rem;
border: 2px solid #6d0026;
width: 10rem;
padding: 0.15rem;
margin: auto;
display: block;
color: #6d0026;
text-align: center;
}
#calculator input:focus {
outline: none;
}
#calculator button {
font: inherit;
background: #6d0026;
color: white;
border: 1px solid #6d0026;
padding: 1rem;
cursor: pointer;
}
#calculator button:focus {
outline: none;
}
#calculator button:hover,
#calculator button:active {
background: #6d2d1b;
border-color: #6d2d1b;
}
#calc-actions button {
width: 4rem;
}
#calc-actions {
margin-top: 1rem;
text-align: center;
}
.credit {
margin: 70px 0 0 0;
text-align: center;
}
app.js
// Base Variables
let result = 0;
let number = 0;
//Store equation as string
let calculationDescription = "";
//Event listeners
document.querySelector("#btn-add").addEventListener('click', sumNumbs);
document.querySelector("#btn-subtract").addEventListener('click', subtractNumbs);
document.querySelector("#btn-multiply").addEventListener('click', multiplyNumbs);
document.querySelector("#btn-divide").addEventListener('click', divideNumbs);
document.querySelector("#btn-equals").addEventListener('click', equals);
document.querySelector('#input-number').addEventListener('keypress', numbersInput);
function numbersInput(e) {
if(e.key === 'Enter' && userInput !== null) {
number = e.target.value;
e.target.value = '';
calculationDescription += number + " ";
console.log(calculationDescription);
}
}
function sumNumbs() {
calculationDescription += "+ ";
}
function subtractNumbs() {
calculationDescription += "- ";
}
function multiplyNumbs() {
calculationDescription += "x ";
}
function divideNumbs() {
calculationDescription += "/ ";
}
function equals() {
let finalCalculation = calculationDescription.split(" ");
//Goes to errorHandler to remove whitespace and make array ready for equation
errorHandler.removeWhiteSpace(finalCalculation);
}
errorHandler.js
class errorHandler {
static removeWhiteSpace(arraySplit) {
return console.log(arraySplit);
}
}
vendor.js(this one isn't to important for the solution)
const userInput = document.getElementById('input-number');
const addBtn = document.getElementById('btn-add');
const subtractBtn = document.getElementById('btn-subtract');
const multiplyBtn = document.getElementById('btn-multiply');
const divideBtn = document.getElementById('btn-divide');
const equalsBtn = document.getElementById('btn-equals');
const currentResultOutput = document.getElementById('current-result');
const currentCalculationOutput = document.getElementById('current-calculation');
function outputResult(result, text) {
currentResultOutput.textContent = result;
currentCalculationOutput.textContent = text;
}
So in my equals method I'd like to send the array finalCalculation which is in the app.js class into the removeWhiteSpace method that's in my errorHandler.js
This is the error I keep getting
app.js:44 Uncaught ReferenceError: errorHandler is not defined
at HTMLButtonElement.equals (app.js:44)
I've tried turning both of them into classes and then creating a constructor with an instance variable for errorHandler to take in the array, but that doesn't seem to work.
I am trying to learn JavaScript; this is what I made for a test. My problem is that I want to count my table rows, but when I remove a table name it should adapt the table row numbers.
Is there someone who can tell me how I should or could do this? If you have a comment about my coding please give it as I want to learn as much as possible.
var count = 0;
var btn = document.getElementById("btn");
var table = document.getElementById("table");
var removeRowBtn = document.getElementById("removeRowBtn");
var tableNr = document.getElementById("tableNr");
// input fields Variable
var firstName = document.getElementsByName("firstName")[0];
var lastName = document.getElementsByName("lastName")[0];
var Age = document.getElementsByName("Age")[0];
var Country = document.getElementsByName("Country")[0];
var AgeCheck = document.myForm.Age.valueOf;
// this function is checking if the input fields have the recuired data in it other wise it give's a error.
function validate() {
// first name field check + error
if( document.myForm.firstName.value == "" ) {
alert( "Please provide your first name!" );
document.myForm.firstName.focus() ;
return false;
}
// last name field check + error message
if( document.myForm.lastName.value == "" ) {
alert( "Please provide your last name!" );
document.myForm.lastName.focus() ;
return false;
}
// age field check + error message
if( isNaN(document.myForm.Age.value) || document.myForm.Age.value < 1 || document.myForm.Age.value > 100 ){
alert( "Please provide your age!");
return false;
}
// country select list check + error message
if( document.myForm.Country.value == "chooseCountry" ) {
alert( "Please provide your country!" );
return false;
}
// if evry thing is true return a value of true
return true;
}
function tableFunction() {
// if validate is true go
if( validate() ){
// count to see how many row's there are added
count++;
// making a new Row
var newRow = document.createElement("tr");
// adding the tow to the Table
table.appendChild(newRow);
// adding a class and a count-id to the Row
newRow.className = "tableRow";
newRow.setAttribute ("id", count);
// adding 4 td to the tr
for(i = 0; i < 5; i++ ){
var newData = document.createElement("td");
newRow.appendChild(newData);
newData.className = "tableData";
// check the td count and place data in.
if(i == 0){
table.getElementsByTagName("tr")[count].getElementsByTagName("td")[i].innerHTML = count;
} else if (i == 1) {
table.getElementsByTagName("tr")[count].getElementsByTagName("td")[i].innerHTML = firstName.value;
} else if (i == 2) {
table.getElementsByTagName("tr")[count].getElementsByTagName("td")[i].innerHTML = lastName.value;
} else if (i == 3) {
table.getElementsByTagName("tr")[count].getElementsByTagName("td")[i].innerHTML = Age.value;
} else if (i == 4){
table.getElementsByTagName("tr")[count].getElementsByTagName("td")[i].innerHTML = Country.value;
}
}
}
}
function removeTableRow(){
i = tableNr.value;
// if there is no table number filled in show a error alert
if( i == "" ) {
alert( "Please provide a table number!" );
tableNr.focus() ;
return false;
}
// find the chosen array
var row = table.getElementsByTagName("tr")[i];
// if the number is not in the row show error alert that it issen't in the table
if( row == undefined ){
alert( "this row number is not in the table" );
return false;
}
row.remove(row.selectedIndex);
}
removeRowBtn.onclick = function() {removeTableRow()};
btn.onclick = function(){ tableFunction()};
body{
background: white;
}
img{
height: 100%;
display: block;
margin: 0 auto;
}
p{
text-align: center;
}
.container{
width: 100%;
max-width: 600px;
border-radius: 2px;
margin: 0 auto;
margin-top: 8vh;
background: lightgray;
box-shadow: 0px 4px 4px darkgray;
}
table{
width: 100%;
text-align: center;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
/* Button */
.btn {
display: inline-block;
margin: 1em auto;
font-weight: 100;
padding: 1em 1.25em;
text-align: center;
width: 100% ;
border-radius: 1px;
position: relative;
z-index: 0;
cursor: pointer;
border: none;
background: #0c84e4;
box-shadow: 0px 1px 1px #063e6b;
color: #FFFFFF;
}
:focus {
outline: -webkit-focus-ring-color auto 0px;
}
.btn.red{
background:red;
width: 100%;
}
/* input field style's */
input[type=text] {
width: calc(25% - 8px);
padding: 12px 20px 12px 5px;
margin: 8px 4px;
box-sizing: border-box;
float: left;
border: none;
border-bottom: 2px solid #536DFE;
text-align: center;
background: transparent;
}
input:focus{
outline: none;
color: black;
}
::-webkit-input-placeholder{
color:black;
font: helvetica 12px bold ;
text-align: center;
}
select{
width: calc(25% - 8px);
padding: 12px 20px 12px 5px;
margin: 8px 4px;
box-sizing: border-box;
float: left;
border: none;
border-bottom: 2px solid #536DFE;
text-align: center;
background: transparent;
height: 39px;
border-radius: 0px !important;
}
<!DOCTYPE html>
<html>
<head>
<title>Inzend Opgave H5</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<!-- style sheets -->
<link href="style.css" rel="stylesheet" type="text/css" >
</head>
<body>
<div id="wrapper">
<section class="container">
<form id="personInfo" name="myForm">
<table>
<tbody id="table">
<tr>
<td>nr.</td>
<td>First Name</td>
<td>Last Name</td>
<td>Age</td>
<td>Country</td>
</tr>
</tbody>
</table>
<input type="text" name="firstName" placeholder="firstName">
<input type="text" name="lastName" placeholder="lastName">
<input type="text" name="Age" placeholder="Age">
<select name="Country">
<option value="choose a country">Kies een land</option>
<option value="Nederland">NL</option>
<option value="Belgie">BE</option>
<option value="Duitsland">DE</option>
</select>
<input type="button" name="button" id="btn" class="btn" value="Add the input fields to the table">
<p>To remove a table number fill in the input field with the <br> number of the table and click remove table row</p>
<input type="button" name="button" id="removeRowBtn" class="btn" value="remove table row" style="width: 75%;">
<input type="text" name="TableNr" id="tableNr" placeholder="table nr.">
</form>
</section>
</div>
<!-- java-scripts -->
<script type="text/javascript" src="script.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.2.js"></script>
<script type="text/javascript">
var cw = $('.container').width();
$('.container').css({
'height': cw + 'px'
});
</script>
</body>
</html>
Change
row.remove(row.selectedIndex);
to
row.remove(row.selectedIndex);
var rows = document.querySelectorAll("#table tr");
for (var i = 1; i < rows.length; i++) { rows[i].cells[0].innerText = i; }
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/