this JavaScript log in wont work - javascript

i found and edited this code from this website for practice but the code wont work with me. the goal of the code is to create a username and password on one page (which for now is limited to premade usernames and passwords) and send that array of information to another page where you can log in using the username and password from the other page. the code looks fine to me but i am an amateur and want to know what is wrong with it. thank you for your answer.
the code for where the username and password are defined is:
<!DOCTYPE html>
<html>
<head>
<title>
create account
</title>
<script>
sessionStorage.setItem("unArray", JSON.stringify("bob", "sam"));
sessionStorage.setItem("pwArray", JSON.stringify("lol", "jk"));
</script>
</head>
<body>
</body>
</html>
the code for taking the already created username and password from the above page and using that for a log in page is this:
<!DOCTYPE html>
<html>
<head>
<title>
log on page
</title>
<script type = "text/javascript">
var count = 2;
function validate() {
var un = document.getElementById("username").value;
var pw = document.getElementById("pword").value
var valid = false;
var unArray = JSON.parse(sessionStorage.getItem("unArray"));
var pwArray = JSON.parse(vsessionStorage.getItem("pwArray"));
for (var i=0; i <unArray.length; i++) {
if ((un == unArray[i]) && (pw == pwArray[i])) {
valid = true;
break;
}
}
if (valid) {
alert ("Login was successful");
window.location = "http://www.google.com";
return false;
}
var t = " tries";
if (count == 1) {t = " try"}
if (count >= 1) {
alert ("Invalid username and/or password. " +
"You have " + count + t + " left.");
document.myform.username.value = "";
document.myform.pword.value = "";
setTimeout("document.myform.username.focus()", 25);
setTimeout("document.myform.username.select()", 25);
count --;
}
else {
alert ("Still incorrect! You have no more tries left!");
document.myform.username.value = "No more tries allowed!";
document.myform.pword.value = "";
document.myform.username.disabled = true;
document.myform.pword.disabled = true;
return false;
}
}
</script>
<style>
p.log_on{
position: fixed;
top: 30px;
left: 20px;
}
</style>
</head>
<body>
<form name = "myform">
<p class="log_on">
ENTER USER NAME <input type="text" id="username"><br><br><br><br><br>
ENTER PASSWORD <input type="password" id="pword">
<input type="button" value="Check In" id="Submit" onclick="validate()">
</p>
</form>
</body>
</html>

The following two lines:
sessionStorage.setItem("unArray", JSON.stringify("bob", "sam"));
sessionStorage.setItem("pwArray", JSON.stringify("lol", "jk"));
are not using the JSON.stringify function correctly.
They should be:
sessionStorage.setItem("unArray", JSON.stringify(["bob", "sam"]));
sessionStorage.setItem("pwArray", JSON.stringify(["lol", "jk"]));
See the following link for reference: Mozilla Developer Network.
Per the documentation, the JSON.stringify parameters are defined as the following:
Syntax
JSON.stringify(value[, replacer [, space]])
Parameters
value - The value to convert to a JSON string.
replacer (Optional) - If a function, transforms values and properties encountered while stringifying; if an array, specifies the set of properties included in objects in the final string.
A detailed description of the replacer function is provided in the JavaScript guide article Using native JSON.
space (Optional) - Causes the resulting string to be pretty-printed.

Related

Enter key as well as submit button on Google Script Code in Sheet

I would like to be able to use enter as well as the submit button to execute / accept data entry and commit to cell.
I cannot seem to get the code to work.
Any advice how to modify?
<script>
var itemBox = document.getElementById("itemname");
document.getElementById("btn").addEventListener("click",addRecord);
function addRecord(){
var name = itemBox.value;
if(name.trim().length == 0){
M.toast({html: "Please enter a valid barcode!"})
} else{
var data = {
name:itemBox.value
};
google.script.run.appendData(data);
itemBox.value = "";
}
}
</script>
Please read comments:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<script>
var itemBox = document.getElementById("itemname");
document.getElementById("btn").addEventListener("click",addRecord);
function addRecord(){
var name = itemBox.value;//item box is undefined
if(name.trim().length == 0){
M.toast({html: "Please enter a valid barcode!"})//M is undefined and toast does not exist clientside
} else{
var data = {name:itemBox.value};
google.script.run.appendData(data);
itemBox.value = "";
}
}
</script>
</body>
</html>
Spreadsheet.toast() is a server side method of Class Spreadsheet and is not intended to function clientside on the browser.
Spreadsheet.toast()
So far your description of your question is incomplete

Uncaught TypeError: google.script.run.doSomething is not a function

I am trying to check if the input name is already in a Google Sheet. However, I am getting this error:
Uncaught TypeError: google.script.run.doSomething is not a function.
Here is my Index.html file.
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<meta charset="UTF-8">
</head>
<body>
<input type="text" id="meetingTitle" value=""> // Getting value here
<button onclick="checkName()">Check if available</button> //Calling function is is causing the error.
<p id=nameVerification><i>Click the button above to check availability.</i></p>
<script>
function checkName() {
var toPass = document.getElementById("meetingTitle").value;
prompt("toPass " + toPass);
google.script.run.doSomething();
}
function checkNameCS(checkNameSSReturn) {
if (checkNameSSReturn == "") {
document.getElementById('nameVerification').innerHTML = "Already in Use: Please try with another name."
document.getElementById("meetingTitle").value = "";
} else {
document.getElementById("meetingTitle").value = checkNameSSReturn;
document.getElementById('nameVerification').innerHTML = "Meeting name available. Procced."
}
}
function doSomething () {
var nameGiven = document.getElementById("meetingTitle").value;
var nameExists = false;
var nameVerified = false;
var name = nameGiven.toLowerCase();
name = strip(name);
prompt("name " + name);
var spreadsheetId = ''; //Sheet id entered
var rangeName = 'Sheet1';
var values = Sheets.Spreadsheets.Values.get(spreadsheetId, rangeName).values;
if (!values) {} else {
for (var row = 0; row < values.length; row++) {
if (name == values[row][0]) {
nameExists = true;
}
}
}
if (nameExists) {
checkNameCS("");
prompt("name2 " + " ");
return;
}
nameVerified = true;
prompt("name2 " + name);
checkNameCS(name);
return;
}
function strip(str) {
return str.replace(/^\s+|\s+$/g, '');
}
</script>
</body>
</html>
I tried debuging it with prompts but with no success. It seems like the function do something is properly called. But the code stops working aftergoogle.script.run.doSomething();.
I have looked at the documentation for successhandlers but they dont solve the issue either.
How about this modification?
Issue of your script:
doSomething() of google.script.run.doSomething() is required to be Google Apps Script.
In your script, doSomething() is put in HTML (index.html), and a method for using Google Apps Script is included. When google.script.run.doSomething() is run, doSomething() cannot be found at Google Apps Script (code.gs). By this, such error occurs. And if doSomething() is run at HTML side, also an error occurs at Sheets.Spreadsheets.Values.get(), because Sheets.Spreadsheets.Values.get() is the method of Advanced Google Services with Google Apps Script.
If you put it to Google Apps Script (code.gs), Javascript which is used at the script of doSomething() is required to be modified.
Modified script:
In this modification, your script was separated to Google Apps Script (code.gs) and HTML (index.html). var nameGiven = document.getElementById("meetingTitle").value; and checkNameCS(name); are used in index.html.
By the way, before you run this script, please enable Sheets API at Advanced Google Services.
Google Apps Script: code.gs
function strip(str) {
return str.replace(/^\s+|\s+$/g, '');
}
function doSomething (nameGiven) {
var nameExists = false;
var nameVerified = false;
var name = nameGiven.toLowerCase();
name = strip(name);
var spreadsheetId = '###'; //Sheet id entered
var rangeName = 'Sheet1';
var values = Sheets.Spreadsheets.Values.get(spreadsheetId, rangeName).values;
if (values) {
for (var row = 0; row < values.length; row++) {
if (name == values[row][0]) {
nameExists = true;
}
}
}
if (nameExists) {
return "";
}
nameVerified = true;
return name;
}
HTML: index.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<meta charset="UTF-8">
</head>
<body>
<input type="text" id="meetingTitle" value="">
<button onclick="checkName()">Check if available</button>
<p id=nameVerification><i>Click the button above to check availability.</i></p>
<script>
function checkName() {
var toPass = document.getElementById("meetingTitle").value;
prompt("toPass " + toPass);
var nameGiven = document.getElementById("meetingTitle").value; // Added
google.script.run.withSuccessHandler(checkNameCS).doSomething(nameGiven); // Modified
}
function checkNameCS(checkNameSSReturn) {
console.log(checkNameSSReturn)
if (checkNameSSReturn == "") {
document.getElementById('nameVerification').innerHTML = "Already in Use: Please try with another name."
document.getElementById("meetingTitle").value = "";
} else {
document.getElementById("meetingTitle").value = checkNameSSReturn;
document.getElementById('nameVerification').innerHTML = "Meeting name available. Procced."
}
}
</script>
</body>
</html>
Reference:
Class google.script.run

Output of Ajax response

My jsp page contains an array of food with 4 items in it.
When the user enters a food name in the text box which exists in the array I get a output with 4 strings stating whether it is found or not.
Depending on the position of the food item in the array I get the actual answer in the respective string. If the food item entered is the 4th element in array then 4th string written by AJAX gives the correct answer.
My screenshots show the issue
showing the output in case the value entered is Samosa Pav,the second string gives the right output.
showing the output in case the value entered is misalPav,the fourth string gives the right output
What changes so I need to make to ensure that only one and the correct output is received from AJAX call?
var request;
function sendInfo() {
var v = document.getElementById("userInput").value;
var url = "index.jsp?food=" + v;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
} else if (window.ActiveXObject) {
request = new ActiveXObject("Microsoft.XMLHTTP");
}
if (request.readyState == 0 || request.readyState == 4) {
try {
request.onreadystatechange = getInfo;
request.open("GET", url, true);
request.send();
} catch (e) {
alert("Unable to connect to server");
}
}
}
function getInfo() {
if (request.readyState == 4) {
if (request.status == 200) {
var val = request.responseText;
document.getElementById('underInput').innerHTML = val;
}
}
}
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<script type="text/javascript" src="food.js">
</script>
</head>
<body>
<h3>The Chuff Bucket</h3>
Enter the food you want to order
<input type="text" id="userInput" name="input" onkeyup="sendInfo()"></input>
<div id="underInput"></div>
</body>
</html>
%--
Document : index
Created on : 15 Dec, 2016, 7:07:55 PM
Author : KRISHNAJI
--%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%
String food = request.getParameter("food");
String foodArray[] = {"Vada Pav", "Samosa Pav", "Pav Bhaji", "Misal Pav"};
for(int i = 0; i < foodArray.length; i++)
{
if(food.equalsIgnoreCase(foodArray[i]))
{
out.println("Hey we do have " + food);
}
else if (food == "")
{
out.println("Enter a food");
}
else
{
out.println("We don't have " + food);
}
}
%>
</body>
</html>
[1]: https://i.stack.imgur.com/sBHnZ.jpg
[2]: https://i.stack.imgur.com/Xv7fG.jpg
I will just edit the important bits here:
String food = request.getParameter("food");
String foodArray[] = {"Vada Pav", "Samosa Pav", "Pav Bhaji", "Misal Pav"};
int i = 0;
for(i = 0; i < foodArray.length; i++)
{
if(food.equalsIgnoreCase(foodArray[i]))
{
out.println("Hey we do have " + food);
break;
}
else if (food == "")
{
out.println("Enter a food");
break;
}
}
if(i >= foodArray.length)
{
out.println("We don't have " + food);
}
Right, in my comment I forgot that all other conditions in your original loop will still print because of the else statement. So I now declared your counter outside of the loop and compared to the length of the array after the loop is exited. That way, if the food they entered is not found, it will only print once at the end. If input is blank, or matches a food, the conditions will be met and it will print the correct response. The counter will cease to increment and will be less than the length of the array, failing the last condition, and leaving you with only the correct response. This should answer your question fully.

Palindrome incorrect results.

I'm trying to create a palindrome checker. And now it seems that my lengthChecker() is no longer being called, nor is the condition whenever a word isn't a palindrome, then say it's not a palindrome. What could be the issue?
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Lesson #6 Homework</title>
<script type="text/javascript" src="./js/palindrome.js"></script>
</head>
<body>
<h1>Is it a Palindrome?</h1>
<div id="mainCont">
<p>Hello. Please enter a word, and I'll see if it is a palindrome.</p>
<p>Word:
<input type="text" id="str" name="string" />
<button id="checkInput">Submit</button>
</p>
</div>
</body>
</html>
Here is the JS as of now:
function lengthChecker() {
var str = document.getElementById("str").value;
if (str.length > 10 ) {
alert("Sorry. Your input surpasses the 10 characters maximum. Please try again.")
return false;
} else if (str.length == 0) {
alert ("Sorry. Your input is too short, and doesn't meet the 10 characters maximum. Please try again.")
return false;
}
palindrome();
}
function palindrome() {
var revStr = "";
var str = document.getElementById("str").value;
var i = str.length;
for (var j = i; j >= 0; j--) {
revStr = revStr + str.charAt(j);
}
if (str == revStr) {
isPalindrome();
} else {
alert(str + " -is not a Palindrome");
}
}
function isPalindrome() {
alert(str + " is a Palindrome.");
}
document.addEventListener("DOMContentLoaded" , function(e){
var el = document.getElementById("checkInput");
el.addEventListener("click", isPalindrome);
});
You have your Javascript linked in the head element, so it is executed before the <button id="checkInput"> gets into the DOM. Move it to the end of body or make it deferred.
Because you are tying to access your button, before your page is properly loaded.
You need to get your button and bind your event handler, when DOM is loaded.
document.addEventListener("DOMContentLoaded", function(e) {
var el = document.getElementById("checkInput");
el.addEventListener("click", isPalindrome);
});

How Do You Run the ENTIRE Javascript Page From An Button In HTML?

I have been trying to make all my Javascript Page code from JSBin to work automatically upon the clicking of a button. Problems include not being able to run the code because it says I have multiple variables in my script that do not work together and not being able to put it all in HTML because console.log doesn't work. I tried a couple different ideas, but sadly, I am unable to do it correctly.
My Code Is:
var name = prompt('So what is your name?');
var confirmName = confirm('So your name is ' + UCFL(name) + '?');
function UCFL(string) {
return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
}
if (confirmName === true) {
var start = confirm('Good. Lets start the roleplay, Sir ' + UCFL(name) + '. Are you
ready?');
}
if (confirmName === false) {
var name = prompt('Than what is your name?');
var confirmNamed = confirm('So your name is ' + UCFL(name) + '?');
}
if (confirmNamed === true) {
var start = confirm('Good. Lets start the roleplay, Sir ' + UCFL(name) + '. Are you
ready?');
}
if (confirmNamed === false) {
var name = prompt('Than what is your name?');
var confirmName = confirm('So your name is ' + UCFL(name) + '?');
if (confirmName === true) {
var start = confirm('Good. Lets start the roleplay, Sir ' + UCFL(name) + '. Are you
ready?');
}
if (confirmName === false) {
alert('Oh, guess what? I do not even fucking care what your name is anymore. Lets just
start..');
var start = confirm('Are you ready?');
}
}
if (start === true) {
var x = console.log(Math.floor(Math.random() * 5));
if (x === 1) {
alert('You are an dwarf in a time of great disease.');
alert('');
}
}
And this is what I want you to fix:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<form>
<input type="button" value="Start The Game" onclick="" />
</form>
</body>
</html>
I've created an entry on JSBin suggesting many improvements to what you have now:
http://jsbin.com/epurul/3/edit
Visit the entry to test the code yourself. Here is the content, for convenience:
HTML:
<body>
<button onclick="playGame()">Play Game</button>
</body>
And JavaScript:
// Expose playGame as a top-level function so that it can be accessed in the
// onclick handler for the 'Play Game' button in your HTML.
window.playGame = function() {
// I would generally recommend defining your functions before you use them.
// (This is just a matter of taste, though.)
function UCFL(string) {
return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
}
// Rather than capitalize name everywhere it is used, just do it once
// and then use the result everywhere else.
function getName(message) {
return UCFL(prompt(message));
}
var name = getName('So what is your name?');
// Don't repeat yourself:
// If you're writing the same code in multiple places, try consolidating it
// into one place.
var nameAttempts = 0;
while (!confirm('So your name is ' + name + '?') && ++nameAttempts < 3) {
// Don't use 'var' again as your name variable is already declared.
name = getName('Then what is your name?');
}
if (nameAttempts < 3) {
alert('Good. Lets start the roleplay, Sir ' + name + '.');
} else {
alert("Oh, guess what? I do not even fucking care what your name is anymore. Let's just start...");
}
};
Put your code in a function, for example:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
<script>
function runGame() {
// put your js code here
}
</script>
</head>
<body>
<form>
<input type="button" value="Start The Game" onclick="runGame();" />
</form>
</body>
</html>
It would also be a good idea to copy your js code to another file and import that using a script tag, for instance:
<script src="path/to/file.js"></script>

Categories