I made a code for my website with session and local storage. Though it seems it's not working and i don't know what is the problem. I tried everything to make it work but i can't. The problem is that you can register the local and session storage can save your details but i can't do the login. The login button is always disabled.
HTML CODE:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="logreg.js"></script>
</head>
<body>
<script>
document.write(outstate(isative()));
</script>
<form>
<input type="email" id="user" onblur="verlogin()" required>
<input type="password" id="pass" onblur="verlogin()" required>
<span id="mess"></span>
<button type="submit" disabled id="login" onclick="login();">LOGIN</button>
</form>
<input type="email" id="usermail" onblur="veruser();ch();" required>
<span id="veruser"></span>
<button style="text-decoration: none!important;display: none;" id="uservalue" value="0"></button>
<input type="password" id="password" onblur="verpass();ch();" required>
<input type="password" id="confirmpassword" onblur="verpass();ch();" required>
<span id="verpass"></span>
<button style="text-decoration: none!important;display: none;" id="passvalue" value="0"></button>
<input type="text" id="morada" required>
<input type="number" maxlength="9" id="nif" required>
<button type="submit" id="registar" onclick="registar();">REGISTER</button>
</body>
</html>
JAVASCRIPT CODE:
window.onload=function(){
if(sessionStorage.length==0){
var key='';
for(var i=0;i<localStorage.length;i++){
key = localStorage.key(i);
sessionStorage.setItem(key,'');
}
}
}
function verlogin(){
var nome=document.getElementById('user').value;
var pass=document.getElementById('pass').value;
document.getElementById('mess').innerHTML = '';
var key='';
var val='';
if(localStorage.length!=0){
for(var i=0;i<localStorage.length;i++){
key = localStorage.key(i);
val = localStorage.getItem(key);
if(nome!='' || pass!=''){
if(nome==key){
if(val.substr(0, val.indexOf('|'))==pass) {
document.getElementById('mess').style.color='green';
document.getElementById('mess').innerHTML = 'VALID';
document.getElementById("login").disabled = false;
}else{
document.getElementById("login").disabled = true;
document.getElementById('mess').style.color='red';
document.getElementById('mess').innerHTML = 'User or Wrong Password';
}
}else{
document.getElementById("login").disabled = true;
document.getElementById('mess').style.color='red';
document.getElementById('mess').innerHTML = 'User or Wrong Password';
}
}else{
document.getElementById('mess').innerHTML = '';
}
}
}else{
document.getElementById("login").disabled = true;
document.getElementById('mess').style.color='red';
document.getElementById('mess').innerHTML = 'Create an Account';
}
}
function login(){
var nome=document.getElementById('user').value;
sessionStorage.setItem(nome,'ativo');
window.location.href='index.html';
}
function veruser(){
var nome=document.getElementById('usermail').value;
document.getElementById('uservalue').value = 0;
var key='';
if(localStorage.length!=0) {
for (var i = 0; i < localStorage.length; i++) {
key = localStorage.key(i);
if (nome != '') {
if (nome == key) {
document.getElementById('uservalue').value = 0;
document.getElementById('veruser').style.color = 'red';
document.getElementById('veruser').innerHTML = 'User already in use';
} else {
document.getElementById('uservalue').value = 1;
document.getElementById('veruser').style.color = 'green';
document.getElementById('veruser').innerHTML = 'Valid';
}
} else {
document.getElementById('veruser').innerHTML = '';
}
}
}else{
document.getElementById('uservalue').value = 1;
document.getElementById('veruser').style.color = 'green';
document.getElementById('veruser').innerHTML = 'Valid';
}
}
function ch(){
var verp = document.getElementById('passvalue').value;
var veru = document.getElementById('uservalue').value;
document.getElementById("login").disabled = true;
if(verp==1 && veru==1){
document.getElementById("registar").disabled = false;
}else{
document.getElementById("login").disabled = true;
}
}
function verpass(){
var pass1=document.getElementById('password').value;
var pass2=document.getElementById('confirmpassword').value;
document.getElementById('passvalue').value = 0;
if(pass1!='' || pass2!=''){
if(pass1!=pass2){
document.getElementById('passvalue').value = 0;
document.getElementById('verpass').style.color='red';
document.getElementById('verpass').innerHTML = 'Passwords don't match';
}else{
document.getElementById('passvalue').value = 1;
document.getElementById('verpass').style.color='green';
document.getElementById('verpass').innerHTML = 'Valid';
}
}else{
document.getElementById('veruser').innerHTML = '';
}
}
function registar(){
var verp = document.getElementById('passvalue').value;
var veru = document.getElementById('uservalue').value;
var user=document.getElementById('usermail').value;
var pass=document.getElementById('password').value;
var mor=document.getElementById('morada').value;
var nif=document.getElementById('nif').value;
if(verp=='1' && veru=='1'){
localStorage.setItem(user,pass + '|'+mor);
sessionStorage.setItem(user,'ativo');
window.location.href='index.html';
}else{
alert('ERRO');
}
}
function logout(){
var key='';
var val='';
for(var i=0;i<sessionStorage.length;i++){
key = sessionStorage.key(i);
val = sessionStorage.getItem(key);
if(val=='ativo'){
sessionStorage.setItem(key,'');
window.location.href='index.html';
}
}
}
function isative(){
var key='';
var val='';
var user='';
for(var i=0;i<sessionStorage.length;i++){
key = sessionStorage.key(i);
val = sessionStorage.getItem(key);
if(val=='ativo'){
user = key;
}else{
user=0;
}
}
return user;
}
function outstate(ative){
var content='';
if(ative!=0){
alert(ative);
content+= '<h6>The user ' + ative+' is online<h6>';
content +='<button type="submit" onclick="logout();">LOGOUT</button>'
}else{
content +='<h6>Not Connected<h6>';
}
return content
}
I don't know what to do anymore... :(
Related
I have a webapp that retrieves from a Google sheet an array of values to dynamically create a table so if the array retrieved has four items, then the table has four rows, and so on.Each row has as first column item a toggle to disables the other columns' input fields for that row.
It looks like this:
I initially created everything statically, just to get it working first, with five sample rows, and got every thing working, the toggle worked and disabled and cleared content, etc. However, as I wrote in the part to dynamically create the table rows and the event listeners for each toggle, the toggle stopped responding, even though the function for each is named correctly according to the dynamically created event listeners.
These rows are done in the javascript for the page, using this statement:
document.addEventListener('DOMContentLoaded', setup_ui);
After creating the table rows and before the end of the setup_ui function, I create the event listeners for each toggle.
// Next we need to create event listeners to make the toggles usables
for(var i = 0; i < domains_count; i++){
let number = i+1;
let domain_toggle = `domain${number}`;
let function_name = `switch_for_dom${number}`;
document.getElementById(domain_toggle).addEventListener("click",function_name);
}
You see, at this point, I do have the rows created, they show up, all appears well. And yet, if I do
alert(document.getElementById("domain1"))
It doesn't find it... even though its in front of me and I can right click on the page, go into dev tools and see it there.
The code for the function handling the toggle is there below in the file, here's the first function for the first toggle.
function switch_for_dom1(){
let check = document.getElementById("domain1");
if(check.checked == true){
document.getElementById("first_name_domain1").disabled = false;
document.getElementById("last_name_domain1").disabled = false;
document.getElementById("email_domain1").disabled = false;
document.getElementById("phone_domain1").disabled = false;
document.getElementById("position_domain1").disabled = false;
document.getElementById("role_domain1").disabled = false;
}else{
document.getElementById("first_name_domain1").disabled = true;
document.getElementById("last_name_domain1").disabled = true;
document.getElementById("email_domain1").disabled = true;
document.getElementById("phone_domain1").disabled = true;
document.getElementById("position_domain1").disabled = true;
document.getElementById("role_domain1").disabled = true;
document.getElementById("first_name_domain1").value = "";
document.getElementById("last_name_domain1").value = "";
document.getElementById("email_domain1").value = "";
document.getElementById("phone_domain1").value = "";
document.getElementById("position_domain1").value = "";
document.getElementById("role_domain1").value = "Role";
}
}
How can I not only create those table rows dynamically, as I have done here, but also have the event listeners I create dynamically actually work with the functions that are later down in that js file?
I will have to eventually have the functions to handle the toggles created dynamically as well and I have no clue at this point.
To replicate this you'd need yourself a new AppScript project webapp.
Here's the code for my html and js.
HTML:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<?!= include('menu-css'); ?>
<?!= include('users-css'); ?>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
</head>
<body class="body">
<?!= include('menu'); ?>
<div class="user-create-form">
<h5 id="title"> Create User</h5> </br>
<div class="row g-3">
<div class="col-sm-3">
<input type="text" class="form-control" placeholder="first name" aria-label="first name" id="first_name">
</div>
<div class="col-sm-3">
<input type="text" class="form-control" placeholder="last name" aria-label="last name" id="last_name">
</div>
<div class="col-sm">
<input type="text" class="form-control" placeholder="email" aria-label="email" id="email">
</div>
</div>
</br>
<div class="row g-3">
<div class="col-sm-3">
<input type="text" class="form-control" placeholder="Phone number" aria-label="Phone number" id="phone">
</div>
<div class="col-sm-3">
<input type="text" class="form-control" placeholder="Company Position" aria-label="Company Position" id="position">
</div>
<div class="col-sm">
<select class="form-select" aria-label="Default select example" id="role">
<option selected>Role</option>
<option value="1">Superuser</option>
<option value="2">Requester</option>
<option value="3">Reporter</option>
<option value="4">Receiver</option>
<option value="5">Purchaser</option>
<option value="6">Finance</option>
<option value="7">Approver</option>
<option value="8">Peasant</option>
</select>
</div>
</div>
</br>
<div class="toggles">
<div class="form-check form-switch">
<input class="form-check-input" type="checkbox" id="alldomains">
<label class="form-check-label" for="flexSwitchCheckDefault">All Domains</label>
</div>
<table class="table w-auto">
<thead>
<tr>
<th scope="col" class="col col-auto">
Domains
</th>
<th scope="col">
First name
</th>
<th scope="col">
Last name
</th>
<th scope="col">
Email
</th>
<th scope="col">
Phone number
</th>
<th scope="col">
company position
</th>
<th scope="col">
Role
</th>
</tr>
</thead>
<tbody id="tbody">
</tbody>
</table>
</div>
<?!= include('menu-js'); ?>
<?!= include('users-js'); ?>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.3.0-alpha1/dist/js/bootstrap.bundle.min.js" integrity="sha384-w76AqPfDkMBDXo30jS1Sgez6pr3x5MlQ1ZAGC+nuZB+EYdgRZgiwxhTBTkF7CXvN" crossorigin="anonymous"></script>
</body>
</html>
And now the Javascript:
<script>
document.addEventListener('DOMContentLoaded', setup_ui);
function setup_ui(){
var count = 4;
document.getElementById("title").innerHTML = `Create a User across any number of your ${count} domains`;
create_table();
document.getElementById("alldomains").click();
document.getElementById("alldomains").click();
}
google.script.run.withSuccessHandler(create_table).get_domains_names();
function create_table(domains_names){
var domains_count = domains_names.length;
var row_html;
if(domains_count > 0){
var table = document.getElementById("tbody");
var table_body = table.innerHTML;
for(var i = 0; i < domains_count; i++){
let domain = domains_names[i];
let number = i+1;
row_html = `
<tr>
<td>
<div class="form-check form-switch form-check-inline">
<input class="form-check-input" type="checkbox" id="domain${number}">
<label class="form-check-label" for="flexSwitchCheckDefault">${domain}</label>
</div>
<td>
<input type="text" class="form-control" placeholder="first name" aria-label="first name" id="first_name_domain${number}">
</td>
<td>
<input type="text" class="form-control" placeholder="last name" aria-label="last name" id="last_name_domain${number}">
</td>
<td>
<input type="text" class="form-control" placeholder="email" aria-label="email" id="email_domain${number}">
</td>
<td>
<input type="text" class="form-control" placeholder="Phone number" aria-label="Phone number" id="phone_domain${number}">
</td>
<td>
<input type="text" class="form-control" placeholder="Company Position" aria-label="Company Position" id="position_domain${number}">
</td>
<td>
<select class="form-select" aria-label="Default select example" id="role_domain${number}">
<option selected>Role</option>
<option value="1">Superuser</option>
<option value="2">Requester</option>
<option value="3">Reporter</option>
<option value="4">Receiver</option>
<option value="5">Purchaser</option>
<option value="6">Finance</option>
<option value="7">Approver</option>
<option value="8">Peasant</option>
</select>
</td>
</tr>
`;
let row = document.createElement("tr");
row.innerHTML = row_html;
tbody.appendChild(row);
}
// Next we need to create event listeners to make the toggles usables
for(var i = 0; i < domains_count; i++){
let number = i+1;
let domain_toggle = `domain${number}`;
let function_name = `switch_for_dom${number}`;
document.getElementById(domain_toggle).addEventListener("click",function_name);
}
// Next we need to create the functions to provide the functionality for each toggles
}else{ // no domains (they need to add the domains)
}
}
document.getElementById("alldomains").addEventListener("click",applyAllDomains);
function applyAllDomains(){
document.getElementById("domain1").click();
document.getElementById("domain2").click();
document.getElementById("domain3").click();
document.getElementById("domain4").click();
document.getElementById("domain5").click();
switch_for_dom1();
switch_for_dom2();
switch_for_dom3();
switch_for_dom4();
switch_for_dom5();
}
document.getElementById("first_name").addEventListener("input",map_first_name);
document.getElementById("last_name").addEventListener("input",map_last_name);
document.getElementById("email").addEventListener("input",map_email);
document.getElementById("phone").addEventListener("input",map_phone);
document.getElementById("position").addEventListener("input",map_position);
document.getElementById("role").addEventListener("input",map_role);
function map_first_name(){
alert("here");
var fn = document.getElementById("first_name").value;
if(document.getElementById("first_name_domain1").disabled == false){
document.getElementById("first_name_domain1").value = fn;
}
if(document.getElementById("first_name_domain2").disabled == false){
document.getElementById("first_name_domain2").value = fn;
}
if(document.getElementById("first_name_domain3").disabled == false){
document.getElementById("first_name_domain3").value = fn;
}
if(document.getElementById("first_name_domain4").disabled == false){
document.getElementById("first_name_domain4").value = fn;
}
if(document.getElementById("first_name_domain5").disabled == false){
document.getElementById("first_name_domain5").value = fn;
}
}
function map_last_name(){
var fn = document.getElementById("last_name").value;
if(document.getElementById("last_name_domain1").disabled == false){
document.getElementById("last_name_domain1").value = fn;
}
if(document.getElementById("last_name_domain2").disabled == false){
document.getElementById("last_name_domain2").value = fn;
}
if(document.getElementById("last_name_domain3").disabled == false){
document.getElementById("last_name_domain3").value = fn;
}
if(document.getElementById("last_name_domain4").disabled == false){
document.getElementById("last_name_domain4").value = fn;
}
if(document.getElementById("last_name_domain5").disabled == false){
document.getElementById("last_name_domain5").value = fn;
}
}
function map_email(){
var fn = document.getElementById("email").value;
if(document.getElementById("email_domain1").disabled == false){
document.getElementById("email_domain1").value = fn;
}
if(document.getElementById("email_domain2").disabled == false){
document.getElementById("email_domain2").value = fn;
}
if(document.getElementById("email_domain3").disabled == false){
document.getElementById("email_domain3").value = fn;
}
if(document.getElementById("email_domain4").disabled == false){
document.getElementById("email_domain4").value = fn;
}
if(document.getElementById("email_domain5").disabled == false){
document.getElementById("email_domain5").value = fn;
}
}
function map_phone(){
var fn = document.getElementById("phone").value;
if(document.getElementById("phone_domain1").disabled == false){
document.getElementById("phone_domain1").value = fn;
}
if(document.getElementById("phone_domain2").disabled == false){
document.getElementById("phone_domain2").value = fn;
}
if(document.getElementById("phone_domain3").disabled == false){
document.getElementById("phone_domain3").value = fn;
}
if(document.getElementById("phone_domain4").disabled == false){
document.getElementById("phone_domain4").value = fn;
}
if(document.getElementById("phone_domain5").disabled == false){
document.getElementById("phone_domain5").value = fn;
}
}
function map_position(){
var fn = document.getElementById("position").value;
if(document.getElementById("position_domain1").disabled == false){
document.getElementById("position_domain1").value = fn;
}
if(document.getElementById("position_domain2").disabled == false){
document.getElementById("position_domain2").value = fn;
}
if(document.getElementById("position_domain3").disabled == false){
document.getElementById("position_domain3").value = fn;
}
if(document.getElementById("position_domain4").disabled == false){
document.getElementById("position_domain4").value = fn;
}
if(document.getElementById("position_domain5").disabled == false){
document.getElementById("position_domain5").value = fn;
}
}
function map_role(){
var fn = document.getElementById("role").value;
if(document.getElementById("role_domain1").disabled == false){
document.getElementById("role_domain1").value = fn;
}
if(document.getElementById("role_domain2").disabled == false){
document.getElementById("role_domain2").value = fn;
}
if(document.getElementById("role_domain3").disabled == false){
document.getElementById("role_domain3").value = fn;
}
if(document.getElementById("role_domain4").disabled == false){
document.getElementById("role_domain4").value = fn;
}
if(document.getElementById("role_domain5").disabled == false){
document.getElementById("role_domain5").value = fn;
}
}
function switch_for_dom1(){
let check = document.getElementById("domain1");
if(check.checked == true){
document.getElementById("first_name_domain1").disabled = false;
document.getElementById("last_name_domain1").disabled = false;
document.getElementById("email_domain1").disabled = false;
document.getElementById("phone_domain1").disabled = false;
document.getElementById("position_domain1").disabled = false;
document.getElementById("role_domain1").disabled = false;
}else{
document.getElementById("first_name_domain1").disabled = true;
document.getElementById("last_name_domain1").disabled = true;
document.getElementById("email_domain1").disabled = true;
document.getElementById("phone_domain1").disabled = true;
document.getElementById("position_domain1").disabled = true;
document.getElementById("role_domain1").disabled = true;
document.getElementById("first_name_domain1").value = "";
document.getElementById("last_name_domain1").value = "";
document.getElementById("email_domain1").value = "";
document.getElementById("phone_domain1").value = "";
document.getElementById("position_domain1").value = "";
document.getElementById("role_domain1").value = "Role";
}
}
function switch_for_dom2(){
let check = document.getElementById("domain2");
if(check.checked == true){
document.getElementById("first_name_domain2").disabled = false;
document.getElementById("last_name_domain2").disabled = false;
document.getElementById("email_domain2").disabled = false;
document.getElementById("phone_domain2").disabled = false;
document.getElementById("position_domain2").disabled = false;
document.getElementById("role_domain2").disabled = false;
}else{
document.getElementById("first_name_domain2").disabled = true;
document.getElementById("last_name_domain2").disabled = true;
document.getElementById("email_domain2").disabled = true;
document.getElementById("phone_domain2").disabled = true;
document.getElementById("position_domain2").disabled = true;
document.getElementById("role_domain2").disabled = true;
document.getElementById("first_name_domain2").value = "";
document.getElementById("last_name_domain2").value = "";
document.getElementById("email_domain2").value = "";
document.getElementById("phone_domain2").value = "";
document.getElementById("position_domain2").value = "";
document.getElementById("role_domain2").value = "Role";
}
}
function switch_for_dom3(){
let check = document.getElementById("domain3");
if(check.checked == true){
document.getElementById("first_name_domain3").disabled = false;
document.getElementById("last_name_domain3").disabled = false;
document.getElementById("email_domain3").disabled = false;
document.getElementById("phone_domain3").disabled = false;
document.getElementById("position_domain3").disabled = false;
document.getElementById("role_domain3").disabled = false;
}else{
document.getElementById("first_name_domain3").disabled = true;
document.getElementById("last_name_domain3").disabled = true;
document.getElementById("email_domain3").disabled = true;
document.getElementById("phone_domain3").disabled = true;
document.getElementById("position_domain3").disabled = true;
document.getElementById("role_domain3").disabled = true;
document.getElementById("first_name_domain3").value = "";
document.getElementById("last_name_domain3").value = "";
document.getElementById("email_domain3").value = "";
document.getElementById("phone_domain3").value = "";
document.getElementById("position_domain3").value = "";
document.getElementById("role_domain3").value = "Role";
}
}
function switch_for_dom4(){
let check = document.getElementById("domain4");
if(check.checked == true){
document.getElementById("first_name_domain4").disabled = false;
document.getElementById("last_name_domain4").disabled = false;
document.getElementById("email_domain4").disabled = false;
document.getElementById("phone_domain4").disabled = false;
document.getElementById("position_domain4").disabled = false;
document.getElementById("role_domain4").disabled = false;
}else{
document.getElementById("first_name_domain4").disabled = true;
document.getElementById("last_name_domain4").disabled = true;
document.getElementById("email_domain4").disabled = true;
document.getElementById("phone_domain4").disabled = true;
document.getElementById("position_domain4").disabled = true;
document.getElementById("role_domain4").disabled = true;
document.getElementById("first_name_domain4").value = "";
document.getElementById("last_name_domain4").value = "";
document.getElementById("email_domain4").value = "";
document.getElementById("phone_domain4").value = "";
document.getElementById("position_domain4").value = "";
document.getElementById("role_domain4").value = "Role";
}
}
function switch_for_dom5(){
let check = document.getElementById("domain5");
if(check.checked == true){
document.getElementById("first_name_domain5").disabled = false;
document.getElementById("last_name_domain5").disabled = false;
document.getElementById("email_domain5").disabled = false;
document.getElementById("phone_domain5").disabled = false;
document.getElementById("position_domain5").disabled = false;
document.getElementById("role_domain5").disabled = false;
}else{
document.getElementById("first_name_domain5").disabled = true;
document.getElementById("last_name_domain5").disabled = true;
document.getElementById("email_domain5").disabled = true;
document.getElementById("phone_domain5").disabled = true;
document.getElementById("position_domain5").disabled = true;
document.getElementById("role_domain5").disabled = true;
document.getElementById("first_name_domain5").value = "";
document.getElementById("last_name_domain5").value = "";
document.getElementById("email_domain5").value = "";
document.getElementById("phone_domain5").value = "";
document.getElementById("position_domain5").value = "";
document.getElementById("role_domain5").value = "Role";
}
}
</script>
The problem is function_name is a string, rather than the reference to a function.
May I propose you do the following.
const switch_for_dom1 = function () { }
const switch_for_dom2 = function () { }
etc.
Then in
function create_table(domains_names){
.
.
.
let dom_functions = [switch_for_dom1,switch_for_dom2,....];
// Next we need to create event listeners to make the toggles usables
for(var i = 0; i < domains_count; i++){
let number = i+1;
let domain_toggle = `domain${number}`;
let function_name = dom_functions[i];
document.getElementById(domain_toggle).addEventListener("click",function_name);
}
}
here's my code, brand new to coding trying to get the box "points" to return the sum of pointSum if "Ben" is typed into the box "winner". Just trying to work on some basics with this project. Attempting to make a bracket of sorts
<HTLML>
<head>
<script>
var pointSum = 0;
var firstRound = 20;
var secondRound = 50;
var thirdRound = 100;
var fourthRound = 150;
var fifthRound = 250;
var finalRound = 300;
var winnerOne = false;
var winnerTwo = false;
var winnerThree = false;
var winnerFour = false;
var winnerFive = false;
var winnerSix = false;
if (winnerOne = true){
pointSum+=firstRound
} else if (winnerTwo = true){
pointSum+=secondRound
} else if (winnerThree = true){
pointSum+=thirdRound
} else if (winnerFour = true){
pointSum+=fourthRound
} else if (winnerFive = true){
pointSum+=fifthRound
} else if (winnerSix = true){
pointSum+=finalRound
else
function tally() {if document.getElementById('winner') == "Ben" { winnerOne = true;
}
pointSum=document.getElementById("points").value;
}
</script>
</head>
<body>
<form>
Winner:
<input type="text" name="winner" id="winner" size="20">
Points:
<input type="text" name="points" id="points" size="20">
Submit
<button type= "button" onclick="tally()">Tally points</button>
</form>
</body>
</html>
UPDATE***** new code, getting better, not returning console errors but still not getting anything in the "points" box upon clicking tally
<HTLML>
<head>
<script>
var pointSum = 0;
var firstRound = 20;
var secondRound = 50;
var thirdRound = 100;
var fourthRound = 150;
var fifthRound = 250;
var finalRound = 300;
var winnerOne = false;
var winnerTwo = false;
var winnerThree = false;
var winnerFour = false;
var winnerFive = false;
var winnerSix = false;
function tally() {
var winner = document.getElementById("winner").value;
var firstWinner = "Ben";
if (winner == firstWinner){
winnerOne == true;
}
pointSum = document.getElementById("points").value;
}
if (winnerOne == true){
pointSum+=firstRound;
} else if (winnerTwo){
pointSum+=secondRound;
} else if (winnerThree){
pointSum+=thirdRound;
} else if (winnerFour){
pointSum+=fourthRound;
} else if (winnerFive){
pointSum+=fifthRound;
} else if (winnerSix){
pointSum+=finalRound;
}
</script>
</head>
<body>
<form>
Winner:
<input type="text" name="winner" id="winner" size="20">
Points:
<input type="text" name="points" id="points" size="20">
Submit
<button type= "button" onclick="tally()">Tally points</button>
</form>
<div class="updatePoints">
</div>
</body>
</html>
Your code has a few mistakes, lets change it a little bit!
First, you need to access 'value' atribbute of your winner element in your if statement, and surround all the statement in parenthesis
function tally() {
if (document.getElementById('winner').value == "Ben"){
winnerOne = true;
}
pointSum = document.getElementById("points").value;
}
Second, you use '==' to make comparison, you are using '=', it means that you are assign true to variables, and you're forgetting to put ';' at the end of lines! change this part:
if (winnerOne == true){
pointSum+=firstRound;
}
put all of your if/else like the example above!
Hint: when you are using if statement you can use like this:
if (winnerOne){ //you can omit == true, because if winnerOne is true, it will enter ind the if statement
//will enter here if winnerOne is true
}
if (!winnerOne){ //you can omit == false, because if winnerOne is not true, it will enter ind the if statement
//will enter here if winnerOne is false
}
You also have a left over else at the end of your if check which is invalid. You need to end the last else if statement with the };.
Are you trying to out put the text somewhere? I don't see any code that is handling this - you may want to add some HTML that will update like so:
<div class="updatePoints">
// leave empty
</div>
Then within your JavaScript you can always add some code to update the .updatePoints
var points = document.getElementByClass('updatePoints');
points.innerHTML = pointSum.value;
Have add some lines in your code and modify it with some comments. Can try at https://jsfiddle.net/8fhwg6ou/. Hope can help.
<HTLML>
<head>
<script>
var pointSum = 0;
var firstRound = 20;
var secondRound = 50;
var thirdRound = 100;
var fourthRound = 150;
var fifthRound = 250;
var finalRound = 300;
var winnerOne = false;
var winnerTwo = false;
var winnerThree = false;
var winnerFour = false;
var winnerFive = false;
var winnerSix = false;
function tally() {
var winner = document.getElementById("winner").value;
var firstWinner = "Ben";
if (winner == firstWinner){
winnerOne = true; // Use only one = symbol to assign value, not ==
pointSum = Number(document.getElementById("points").value); // moved from outside and convert to number
// This code will update point in Points box
document.getElementById("points").value = tally_pointsum(pointSum);
// The codes below will add the text in div, just remove the + sign if you don't like
document.getElementById("updatePoints").innerHTML += (tally_pointsum(pointSum) - pointSum) + " points added<br />";
}
}
// Wrap codes below become a function, lets call it tally_pointsum:
function tally_pointsum(pointSum) {
if (winnerOne == true){
pointSum+=firstRound;
} else if (winnerTwo){
pointSum+=secondRound;
} else if (winnerThree){
pointSum+=thirdRound;
} else if (winnerFour){
pointSum+=fourthRound;
} else if (winnerFive){
pointSum+=fifthRound;
} else if (winnerSix){
pointSum+=finalRound;
}
return pointSum; //return the sum to caller
}
</script>
</head>
<body>
<form>
Winner:
<input type="text" name="winner" id="winner" size="20">
Points:
<input type="text" name="points" id="points" size="20">
Submit
<button type= "button" onclick="tally()">Tally points</button>
</form>
<!-- change class="updatePoints" to id="updatePoints" for document.getElementById("updatePoints") -->
<div id="updatePoints">
</div>
Happy coding.
I'm working on a web form with several textboxes and a submit button. When the submit button is clicked, I am supposed to verify that the required fields all have input and that the age field is only numeric. For example, the user can enter 56, but 56 years-old, shouldn't be accepted. If the user enters invalid input or leaves required fields blank, the border around the appropriate textboxes should turn red.
However, as my code is written now all the required fields turn red regardless of input. Any ideas how I can fix this and make the page follow the couple of rules I listed?
Most Recent Code
<html>
<head>
<title>Project 4</title>
<style type="text/css">
body {
background-color: black;
color: blue;
text-align: center;
border: 2px double blue;
}
</style>
</head>
<body>
<h1>Welcome to my Web Form!</h1>
<p>
Please fill out the following information.<br>
Please note that fields marked with an asterisk (*) are required.
</p>
<form name="myForm" id="myForm" onsubmit="return validateForm()">
*Last Name: <br>
<input type="text" id="lastname">
<br>
First Name: <br>
<input type="text" id="firstname">
<br>
*Hobbies (separate each hobby with a comma): <br>
<input type="text" id="hobbies">
<br>
Pets:
<div id="petsContainer">
<input type="text" id="pets">
<input type="button" id="addPet" value="Add Pet">
</div>
<br>
Children:
<div id="childContainer">
<input type="text" id="children">
<input type="button" id="addKid" value="Add Child">
</div>
<br>
*Address: <br>
<input type="text" id="address">
<br>
*Phone Number:<br>
<input type="text" id="phone">
<br>
*Age: <br>
<input type="text" id="age">
<br>
<input type="submit" value="Submit">
</form>
<script type="text/javascript">
var validatePhoneOnKeyUpAttached = false;
var validateLNameOnKeyUpAttached = false;
var validateHobbiesOnKeyUpAttached = false;
var validateAddressOnKeyUpAttached = false;
var validateAgeOnKeyUpAttached = false;
function validateForm() {
if(!validatePhoneOnKeyUpAttached) {
document.getElementById("phone").onkeyup = checkPhone;
validatePhoneOnKeyUpAttached = true;
}
else if(!validateLNameOnKeyUpAttached) {
document.getElementById("lastname").onkeyup = checkEmpty;
validateLNameOnKeyUpAttached = true;
}
else if(!validateHobbiesOnKeyUpAttached) {
document.getElementById("hobbies").onkeyup = checkEmpty;
validateHobbiesOnKeyUpAttached = true;
}
else if(!validateAddressOnKeyUpAttached) {
document.getElementById("address").onkeyup = checkEmpty;
validateAddressOnKeyUpAttached = true;
}
else if(!validateAgeOnKeyUpAttached) {
document.getElementById("age").onkeyup = checkEmpty;
document.getElementById("age").onkeyup = checkAge;
validateAgeOnKeyUpAttached = true;
}
return checkEmpty() && checkPhone() && checkAge();
}
function checkPhone() {
var phone = document.forms["myForm"]["phone"].value;
var phoneNum = phone.replace(/[^\d]/g, '');
if(phoneNum.length > 6 && phoneNum.length < 11) {
document.getElementById("phone").style.borderColor="transparent";
return true;
}
else if(phoneNum.length < 7 || phoneNum.length > 10) {
document.getElementById("phone").style.borderColor="red";
return false;
}
}
function checkEmpty() {
var lname = document.forms["myForm"]["lastname"].value;
var pNum = document.forms["myForm"]["phone"].value;
var hobs = document.forms["myForm"]["hobbies"].value;
var live = document.forms["myForm"]["address"].value;
var yr = document.forms["myForm"]["age"].value;
document.getElementById("lastname").style.borderColor = (lname == "") ? "red" : "transparent";
document.getElementById("hobbies").style.borderColor = (hobs == "") ? "red" : "transparent";
document.getElementById("phone").style.borderColor = (pNum == "") ? "red" : "transparent";
document.getElementById("address").style.borderColor = (live == "") ? "red" : "transparent";
document.getElementById("age").style.borderColor = (yr == "") ? "red" : "transparent";
}
function checkAge() {
var age = document.getElementById("age").value;
if(isNan(age)) {
return false;
}
else {
document.getElementById("age").style.borderColor="red";
return true;
}
}
document.getElementById("addPet").onclick=function() {
var div = document.getElementById("petsContainer");
var input = document.createElement("input");
input.type = "text";
input.name = "pats[]";
div.appendChild(document.createElement("br"));
div.appendChild(input);
}
document.getElementById("addKid").onclick=function() {
var div = document.getElementById("childContainer");
var input = document.createElement("input");
input.type = "text";
input.name = "child[]";
div.appendChild(document.createElement("br"));
div.appendChild(input);
}
</script>
</body>
</html>
The problem I'm currently having is that when I click the submit button, all the fields turn red for a split second, but then go back to the regular color and the input is erased. Any thoughts on how to fix this?
By including all of the borderColor="red" statements in a single code block, you're applying that style to all your inputs, even if only one of them failed validation. You need to separate out each statement so that it only applies to the individual field(s) that failed validation:
document.getElementById("lastname").style.borderColor = (lname == "") ? "red" : "transparent";
document.getElementById("phone").style.borderColor = (pNum == "") ? "red" : "transparent";
...
Also, I'm using the ternary operator ? : to clean up the code as well. These statements would replace the if-else block you've written.
I am using the following javascript functions in order to validate my form variables. Hope these will helpful for you.
var W3CDOM = (document.getElementsByTagName && document.createElement);
window.onload = function () {
document.forms[0].onsubmit = function () {
return validate()
}
}
function validate() {
validForm = true;
firstError = null;
errorstring = '';
var x = document.forms[0].elements;
for (var i = 0;i < x.length;i++) {
if (!x[i].value) {
validForm = false;
writeError(x[i], 'This field is required');
}
}
// This can be used to validate input type Email values
/* if (x['email'].value.indexOf('#') == -1) {
validForm = false;
writeError(x['email'],'This is not a valid email address');
}
*/
if (!W3CDOM)
alert(errorstring);
if (firstError)
firstError.focus();
return validForm;
}
function writeError(obj, message) {
validForm = false;
//if (obj.hasError) return false;
if (W3CDOM) {
obj.className += ' error';
obj.onchange = removeError;
var sp = document.createElement('span');
sp.className = 'error';
sp.appendChild(document.createTextNode(message));
obj.parentNode.appendChild(sp);
obj.hasError = sp;
} else {
errorstring += obj.name + ': ' + message + '\n';
obj.hasError = true;
}
if (!firstError)
firstError = obj;
return false;
}
function removeError() {
this.className = this.className.substring(0, this.className.lastIndexOf(' '));
this.parentNode.removeChild(this.hasError);
this.hasError = null;
this.onchange = null;
}
You can call the validations right after the form submission as given below.
<form name="loginForm" action="do.login" method="POST" class="form" onsubmit="return validate();">
I have an easy form. When i submit the form with incorrect informations, the error message appear but i would that the first incorrect input is highlight with focus.
I think how i use .focus() is right but it might doesn't fit with the rest of the function.
Here my code:
<form name="login-registration" onSubmit="return validateForm()" method="post" action="" novalidate >
<div class="span-4">
<label>Email</label>
<label>Your password</label>
<label>Repeat password</label>
<label> <input class="inline check" type="checkbox" id="policy" name="policy" value="policy" /> I agree</label>
</div>
<div class="span-4">
<input type="email" name="emailinput" id="emailinput" value = "<?php echo htmlspecialchars($_POST['emailinput']); ?>"/>
<input type="password" name="pswinput" id="pswinput" value=""/>
<input type="password" name="pswrepeatinput" id="pswrepeatinput" value="" onblur="isValidPswRep()"/>
<input type="submit" name="submit" value="Login" />
</div>
<div class="span-4">
<p id="emptyEmail" class="hidden">Email field is required</p>
<p id="invalidEmail" class="hidden">Email you insert is invalid!</p>
<p id="pswMinMax" class="hidden">Password should be from 4 to 8 caracters</p>
<p id="pswLettNum" class="hidden">Password should be letters and numbers. No special caracters are allow</p>
<p id="pswR" class="hidden">Your passwords is different</p>
<p id="checkN" class="hidden">You must agree to our term</p>
</div>
</form>
And here the script:
function validateForm(){
var email = document.getElementById("emailinput").value;
var psw = document.getElementById("pswinput").value;
var pswrep = document.getElementById("pswrepeatinput").value;
var check = document.getElementById("policy");
if (isValidEmail(email)){
if(isValidPsw(psw,4,8)){
if(isValidPswRep(pswrep)){
if(isValidCheckbox(check)){
return true;
}
}
}
}
return false;
}
function isValidEmail(email) {
var validCharacters = /^\w+#\w+\.\w+$/;
if(email == ""){
var emailErr = document.getElementById("emptyEmail");
emailErr.className = "error";
var emailErr2 = document.getElementById("invalidEmail");
emailErr2.className = "hidden";
return false;
email.focus();
} else if(!validCharacters.test(email)) {
var emailErr = document.getElementById("emptyEmail");
emailErr.className = "hidden";
var emailErr2 = document.getElementById("invalidEmail");
emailErr2.className = "error";
return false;
email.focus();
} else {
var emailErr = document.getElementById("emptyEmail");
emailErr.className = "hidden";
var emailErr2 = document.getElementById("invalidEmail");
emailErr2.className = "hidden";
return true;
}
}
function isValidPsw(psw, minLen, maxLen) {
var lengthPsw = psw.length;
var lettNum = /^[0-9a-zA-Z]+$/;
if(lengthPsw == 0 || lengthPsw <= minLen || lengthPsw > maxLen){
var pswErr = document.getElementById("pswMinMax");
pswErr.className = "error";
var pswErr2 = document.getElementById("pswLettNum");
pswErr2.className = "hidden";
return false;
psw.focus();
} else if(!lettNum.test(psw)){
var pswErr2 = document.getElementById("pswLettNum");
pswErr2.className = "error";
var pswErr = document.getElementById("pswMinMax");
pswErr.className = "error";
return false;
psw.focus();
} else {
var pswErr = document.getElementById("pswMinMax");
pswErr.className = "hidden";
var pswErr2 = document.getElementById("pswLettNum");
pswErr2.className = "hidden";
return true;
}
}
function isValidPswRep(pswrep){
var psw = document.getElementById("pswinput").value;
var pswrep = document.getElementById("pswrepeatinput").value;
if(pswrep != psw){
var pswRepErr = document.getElementById("pswR");
pswRepErr.className = "error";
return false;
pswrep.focus();
}
var pswRepErr = document.getElementById("pswR");
pswRepErr.className = "hidden";
return true;
}
function isValidCheckbox(check){
if (!check.checked){
var checkErr = document.getElementById("checkN");
checkErr.className = "error";
return false;
check.focus();
}
var checkErr = document.getElementById("checkN");
checkErr.className = "hidden";
return true;
}
My code follows:.
<!doctype html>
<html lang="en">
<head>
<title>Testing the textarea</title>
<style type="text/css"></style>
<script type="text/javascript" src="validation.js"></script>
</head>
<body>
<div id="wrapper">
<span id="error_box" style="display:none;"></span>
<form name="storyTeller" method="get" action="#" onSubmit="return validateForm()">
<p class="title">
<label for="title">TITLE:</label>
<input type="text" id="title" name="title" required onBlur="validateTitle(title)"/>
</p>
<textarea name="entry" id="entry" rows="10" cols="45" onBlur="validateEntry(entry)">
</textarea>
<input type="submit" value="submit" />
</form>
</div>
</body>
</html>
Content of validation.js:
function validateTitle(title){/*validating the title*/
if (isNaN(document.getElementById('title').value)){
document.getElementById('title').style.background="#ccffcc";
document.getElementById('error_box').style.display="none";
return true;
}
else{
document.getElementById('error_box').innerHTML='Please enter a valid title';
document.getElementById('error_box').style.display="block";
document.getElementById('title').style.background="red";
return false;
}
}
function validateEntry(entry){/*validating the entry*/
var x=document.getElementById('entry').value;
x = x.trim();
if((x=="")||(x==null)){
document.getElementById('entry').style.background="red";
document.getElementById('error_box').innerHTML = 'Where is your story';
document.getElementById('error_box').style.display="block";
return false;
}
else{
document.getElementById('entry').style.background="#ccffcc";
document.getElementById('error_box').innerHTML='';
document.getELementById('error_box').style.display="none";
return true;
}
}
function validateForm(){/*validating the form*/
var error = 0;
if(!validateTitle('title')){
document.getElementById('error_box').style.display="block";
error++;
}
if(!validateEntry('entry')){
document.getElementById('error_box').style.display="block";
error++;
}
if(error > 0){
return false;
}
}
make the submit button as a normal button; and when it is clicked to call the final validation function, at the end of the function you must submit the form manually if everything is right
example :
<script>
function val(){
if(document.getElementById('tb').value != "")
document.getElementById('frm').submit();
else alert('fill the text field');
}
</script>
<form id="frm" action="#">
<input type="text" id="tb"/>
<input type="button" id="btn" value="submit" onclick="val()"/>
</form>
There is an error in your scrip in function validateEntry()
change line:
document.getELementById('error_box').style.display="none";
to line:
document.getElementById('error_box').style.display="none";
Modified your code so now it works better for both submit and blur events.
In your HTML source change both onblur attributes to onblur="validateEntry(this)" and then you can use this javascript:
function validateEntry(entry) { /*validating*/
var error_box = document.getElementById('error_box');
error_box.style.display = "none";
if (entry.name == "title") { // INPUT type="text"
if (!isNaN(entry.value)) {
error_box.innerHTML = 'Please enter a valid title';
error_box.style.display = "block";
entry.style.background = "#fee";
return false;
} else {
entry.style.background = "#ccffcc";
return true;
}
} else if (entry.name == "entry") { // TEXTAREA
var x = entry.value.trim();
if ((x == "") || (x == null)) {
error_box.innerHTML = 'Where is your story?';
error_box.style.display = "block";
entry.style.background = "#fee";
return false;
} else {
entry.style.background = "#ccffcc";
return true;
}
}
}
function validateForm() { /*validating the form*/
var form = document.forms['storyTeller'];
var error_box = document.getElementById('error_box');
var error = 0;
var error_msg = '';
if (!validateEntry(form['title'])) {
error++;
error_msg += error_box.innerHTML + '<br/>';
}
if (!validateEntry(form['entry'])) {
error++;
error_msg += error_box.innerHTML;
}
if (error > 0) {
error_box.innerHTML = error_msg;
error_box.style.display = "block";
return false;
} else {
error_box.style.display = "none";
return true;
}
}
jsfiddle