I'm making a hangman game and would like to store and retrieve the person's score and their username from the local storage and display it on the leader board div. How do I do this? I've seen most people use localStorage.get and localStorage.set but I'm not sure how to implement it here.
Thanks for the help.
This is my javascript code so far:
function storeUserDetails() {
var userObject = {};
userObject.name = document.getElementById("nameinput").value;
userObject.username = document.getElementById("usernameinput").value;
userObject.password = document.getElementById("passinput").value;
userObject.repeatpassword = document.getElementById("repeatpassinput").value;
userObject.topscore = 0;
localStorage[userObject.username] = JSON.stringify(userObject);
document.getElementById("result").innerHTML = "<b>Registration
Successful<br> Please <a href = '../PHP/login.php'><font color =
'orangered'>login</font></a></b>";
}
function checkLogin() {
if (localStorage.loggedInUsername !== undefined) {
var userObj = JSON.parse(localStorage[localStorage.loggedInUsername]);
}
}
function login() {
var username = document.getElementById("usernameinput").value;
if (localStorage[username] === undefined) {
document.getElementById("result").innerHTML = "<b>Username not found. Please sign up.</b>";
return;
} else {
var userObj = JSON.parse(localStorage[username]); //Convert to object
var password = document.getElementById("passinput").value;
if (password === userObj.password) {
localStorage.loggedInUsername = userObj.username;
document.getElementById("result").innerHTML = "";
window.location = "loggedin.php";
/*sessionStorage.setItem('status', 'logged in');*/
} else {
document.getElementById("result").innerHTML = "<b>Password incorrect. Please try again.</b>"
}
}
}
function updateScore() {
rankingTable = document.getElementById("leaderboardcontainer");
tableData = document.getElementById("content");
//Username and score to be displayed here.
}
You should use getItem, setItem and removeItem methods as shown in the documentation.
https://developer.mozilla.org/it/docs/Web/API/Window/localStorage
Related
I am a beginner in google app script. I am creating a resident payment system where the user can change their password upon logging in. So now, I have done the html part for changing the password but I dont know how to do the coding in order to change the password. I have attached some pictures and my code to explain myself better. Thank you so much guys.
https://docs.google.com/spreadsheets/d/1bM8l6JefFsPrlJnTWf56wOhnuSjdIwg3hMbY1tN1Zp8/edit#gid=1775459006 - Link to google sheet
https://script.google.com/macros/s/AKfycbw_A-XRlXtR9qGNvMKVrorMIg71hwHt0DrHRiNGVYZdURbadYgUtOIkJPsvuYsBK7Fe/exec - Link to Web App
https://script.google.com/d/1DdRKqUX__-ZITUgTZanQ_A7hUL1kcc0TZOeFmn58wYsX_o_7cqNExnYo/edit?usp=sharing - Link to app script
Code for Code.gs
var url = "https://docs.google.com/spreadsheets/d/1bM8l6JefFsPrlJnTWf56wOhnuSjdIwg3hMbY1tN1Zp8/edit#gid=1775459006";
var streetSheetName = "JALAN SANGGUL 4";
function doGet(e) {
var streetSheetName = "JALAN SANGGUL 4"; // Added
PropertiesService.getScriptProperties().setProperty("streetSheetName", streetSheetName); // Added
return HtmlService.createHtmlOutputFromFile('WebAppLogin');
}
function checkLogin(username, password) {
var found_record = '';
var name = '';
var ss = SpreadsheetApp.openByUrl(url);
var webAppSheet = ss.getSheetByName("USERNAMES");
var getLastRow = webAppSheet.getLastRow();
for(var i = 2; i <= getLastRow; i++) {
if(webAppSheet.getRange(i, 1).getValue().toUpperCase() == username.toUpperCase() && webAppSheet.getRange(i, 7).getValue() == password) {
found_record = 'TRUE';
name = webAppSheet.getRange(i, 4).getValue().toUpperCase() + " " + webAppSheet.getRange(i, 5).getValue().toUpperCase();
streetSheetName = webAppSheet.getRange(i, 3).getValue().toUpperCase();
} else if (username.toUpperCase() == 'ADMIN' && password == 'ADMINPASSWORD') {
found_record = 'TRUE';
name = webAppSheet.getRange(i, 4).getValue().toUpperCase() + " " + webAppSheet.getRange(i, 5).getValue().toUpperCase();
streetSheetName = webAppSheet.getRange(i, 3).getValue().toUpperCase();
}
}
PropertiesService.getScriptProperties().setProperty("streetSheetName", streetSheetName); // Added
if(found_record == '') {
found_record = 'FALSE';
}
return [found_record, username,name];
}
function GetRecords(username,filter) {
var filteredDataRangeValues = GetUsernameAssociatedProperties(username);
var resultArray = GetPaymentRecords(filteredDataRangeValues,filter);
return resultArray;
}
function GetUsernameAssociatedProperties(username) {
var filteredDataRangeValues = '';
var ss = SpreadsheetApp.openByUrl(url);
var displaySheet = ss.getSheetByName("USERNAMES");
var dataRangeValues = displaySheet.getDataRange().getValues();
if (username.toUpperCase() == 'ADMIN') {
dataRangeValues.shift();
filteredDataRangeValues = dataRangeValues;
} else {
filteredDataRangeValues = dataRangeValues.filter(row => row[0].toUpperCase() == username.toUpperCase());
}
return filteredDataRangeValues;
}
function GetPaymentRecords(userProperties,filter) {
var streetSheetName = PropertiesService.getScriptProperties().getProperty("streetSheetName"); // Added
var transpose = m => m[0].map((_, i) => m.map(x => x[i]));
var resultArray = [];
var ss = SpreadsheetApp.openByUrl(url);
var displaySheet = ss.getSheetByName(streetSheetName);
var addressValues = displaySheet.getRange("B:C").getValues();
var paidMonthValues = displaySheet.getRange(1, 7, displaySheet.getLastRow(), displaySheet.getLastColumn() - 6).getValues();
//Logger.log(addressValues);
//Logger.log(transpose(paidMonthValues));
userProperties.forEach((v, i) => {
var userHouseNumber = v[1];
var userStreet = v[2];
var column = addressValues.reduce(function callbackFn(accumulator, currentValue, index, array) {
if (currentValue[0] == userHouseNumber && currentValue[1] == userStreet) {
return index
} else {
return accumulator
}
}, '');
//Logger.log(column);
Logger.log(filter)
Logger.log(paidMonthValues);
if(filter=="None"){
var result = transpose(paidMonthValues).map(function callbackFn(element, index, array) {
return [element[0], userHouseNumber, userStreet, element[column] || '']
});
}else{
var result = transpose(paidMonthValues).map(function callbackFn(element, index, array) {
if(element[0].includes(filter))return [element[0], userHouseNumber, userStreet, element[column] || '']
});
}
resultArray = resultArray.concat(result);
//Logger.log(resultArray);
})
//Remove null elements
resultArray = resultArray.filter(element=>{
Logger.log(element!=null)
return element != null;
});
return resultArray;
}
Code for WebAppLogin.html
function changePassword(){
var result = confirm("Want to Change Password?");
if (result) {
google.script.run
.withSuccessHandler(updateButton)
.getEmail()
alert('Password changed');
}
I believe your goal as follows.
When the button of "Change Password" is clicked and input the value and click "Save changes", you want to change the password in the Spreadsheet.
Modification points:
In your script, when "Save changes" button is clicked, it seems that google.script.run.withSuccessHandler(updateButton).getEmail() is run. But, unfortunately, in your script, there are no functions of updateButton and getEmail. By this, an error occurs.
When I saw your shared sample Spreadsheet, it seems that your sample Spreadsheet is different from the sample Spreadsheet of your image. For example, the column "A" of the sheet "USERNAMES" is different. In your shared Spreadsheet, the column "A" is 4.
From this situation, from your replying of it just the same you can notice it now yesterday I mistaken changed it in to 4 sorry about that., I understood that the column "A" of the sheet "USERNAMES" is "USERNAME".
About updateButton, in this answer, alert('Password changed') is run as the sample.
In order to update the password of Spreadsheet, it is required to use the username and the inputted password. And, it is also required to prepare the function at Google Apps Script side.
When above points are reflected to your script, it becomes as follows.
Javascript side:
From:
function GetRecords() {
var spin = "<span class=\"spinner-border spinner-border-sm\" role=\"status\" aria-hidden=\"true\"></span>";
spin += " Loading...";
document.getElementById("LoginButton").innerHTML = spin;
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
To:
var username = ""; // Added
function GetRecords() {
var spin = "<span class=\"spinner-border spinner-border-sm\" role=\"status\" aria-hidden=\"true\"></span>";
spin += " Loading...";
document.getElementById("LoginButton").innerHTML = spin;
username = document.getElementById("username").value; // Modified
var password = document.getElementById("password").value;
And, please modify changePassword() as follows.
function changePassword(){
var result = confirm("Want to Change Password?");
if (result) {
var newPassword = document.getElementById("newPassword").value;
google.script.run.withSuccessHandler(() => alert('Password changed')).changePassword(username, newPassword);
}
}
Google Apps Script side:
Please add the following function to Google Apps Script side.
function changePassword(username, newPassword) {
var sheet = SpreadsheetApp.openByUrl(url).getSheetByName("USERNAMES");
var range = sheet.getRange("A2:A").createTextFinder(username).matchEntireCell(true).findNext();
if (range) {
range.offset(0, 6).setValue(newPassword);
}
}
Note:
In this case, when the password is changed, the alert of "Password changed" can be seen. And, the column "G" of Sheet "USERNAMES" is changed.
I have two buttons: a sign up and a log in. I intend to collect the input form values from the sign up into an array (this works). I then want to compare the user input from the sign up with the user input from the login and notify the user that they are logged in. (I am yet to get started with localStorage and JSON. I want to get this done using arrays first).
I have tried using a for loop and if statements with logical operators (&&).
$(document).ready(function() {
$("#userSignUp").click(function() {
$("#signUpForm").show();
$("#signup").hide();
});
$("#userInfo").click(function(event) {
var custName = $("#newName").val();
var custEmail = $("#newEmail").val();
var custPass = $("#newPass").val();
var custData = [];
custData.push(custName, custEmail, custPass);
$("#userSignUp").text("Thank you for signing up!");
});
$("#userLogIn").click(function() {
$("#loginForm").show();
$("#login").hide();
});
$("#userData").click(function(event) {
var currentName = $("#userName").val();
var currentEmail = $("#userEmail").val();
var currentPass = $("#userPass").val();
for (var i = 0; i < custData.length; i++) {
if ((currentName === custData[0]) && currentEmail === custData[1] && currentPass === custData[2]) {
$("#userLogIn").text("You are logged in!");
} else {
$("#userLogIn").text("Please enter correct name, email and password!");
}
};
});
});
May be you could try only IF statement without the loop.
The following thing checks if there is such item in the array and if it IS, will do smth:
if (custData.indexOf(currentName) != -1
&& custData.indexOf(currentEmail) != -1
&& custData.indexOf(currentPass) != -1) {
$("#userLogIn").text("You are logged in!");
} else {
$("#userLogIn").text("Please enter correct name, email and password!");
I have been learning about localStorage. I decided to use it on this task. I collected the values that the user inputs when signing up, and 'saved' them on local Storage. I then collected the value the user inputs and 'retrieved' them via local Storage. Here is the code:
$(document).ready(function() {
$("#userSignUp").click(function() {
$("#signUpForm").show();
$("#signup").hide();
});
$("#userInfo").click(function(event) {
var custName = $("#newName").val();
var custEmail = $("#newEmail").val();
var custPass = $("#newPass").val();
localStorage.setItem("name", "Raych") +
localStorage.setItem("email", "raych#gmail.com") +
localStorage.setItem("password", "hey"); ;
$("#userSignUp").text("Thank you for signing up!");
});
$("#userLogIn").click(function() {
$("#loginForm").show();
$("#login").hide();
});
$("#userData").click(function(event) {
event.PreventDefault;
var currentName = $("#userName").val();
var currentEmail = $("#userEmail").val();
var currentPass = $("#userPass").val();
localStorage.getItem("name") +
localStorage.getItem("email") +
localStorage.getItem("password");
$("#userLogIn").text("You are logged in!");
});
});
I am creating search bar, which shows results from database dynamically on keypress, when they match the string that is in the search bar. Also when the string doesn't match anything in my database, I want to show message to user, that nothing matches his input. Problem is that I don't know how to do this in javaScript. I tried using callback function, but my implementation doesn't work. It is my first time using callback function, so I guess something is not right. Can anybody help me?
Here is simplified code:
var bars = firebase.database().ref("bars").orderByChild("rating");
var types = firebase.database().ref("types");
var searcher = document.getElementById("searcher");
var results = document.getElementById("searchResults");
function search(){
var value = searcher.value.toUpperCase();
clearTimeout(timeout);
timeout = setTimeout(function () {
if(value == null || value == ""){
results.style.display = "none";
} else{
results.innerHTML = "";
//callback function here
function findResults(callback) {
types.once("value").then(function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var type = childSnapshot.key;
if(type.toUpperCase().startsWith(value)){
results.style.display = "block";
var typeItem = createDiv("result-item");
typeItem.innerHTML = type;
results.append(typeItem);
}
callback(true);
});
});
bars.once("value").then(function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var bar = childSnapshot.key;
if(bar.toUpperCase().startsWith(value)){
results.style.display = "block";
var barItem = createDiv("result-item");
barItem.innerHTML = type;
results.append(barItem);
}
callback(true);
});
});
}
//This needs to work, when callback didn't return true
findResults(function(callback){
if(!callback){
var empty = createDiv("emptyResult");
empty.innerHTML = "No matching results";
results.appendChild(empty);
results.style.display = "block";
}
});
}
}, 400);
}
function createDiv(name){
var div = document.createElement("div");
div.className = name;
return div;
1.Let me start by pointing out that querying the Firebase Database on Keypress can be very expensive, since you'll be downloading data more frequently and Firebase has a price on data downloaded. I recommend querying the database when the user presses Enter or a Search Button.
2.I don't see why you need a callback function for this. You can use plain functions to achieve that. Like this:
function search(){
var value = searcher.value.toUpperCase();
clearTimeout(timeout);
timeout = setTimeout(function () {
if(value == null || value == ""){
results.style.display = "none";
} else{
results.innerHTML = "";
types.once("value").then(function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var type = childSnapshot.key;
var foundUnderTypes = false;
if(type.toUpperCase().startsWith(value)){
results.style.display = "block";
var typeItem = createDiv("result-item");
typeItem.innerHTML = type;
results.append(typeItem);
foundUnderTypes = true;
}
bars.once("value").then(function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var bar = childSnapshot.key;
if(bar.toUpperCase().startsWith(value)){
results.style.display = "block";
var barItem = createDiv("result-item");
barItem.innerHTML = type;
results.append(barItem);
}
else{
if(!foundUnderTypes)
emptyResult();
}
});
});
});
});
}
}, 400);
}
function emptyResult(){
var empty = createDiv("emptyResult");
empty.innerHTML = "No matching results";
results.appendChild(empty);
results.style.display = "block";
}
I am playing around with the local storage on PhoneGap, trying to create a JavaScript login. My current problem is when I run the application, it will not go to the main menu if the username and password is correct.
I believe the problem is with the window.location.href method. I want to navigate to a local page, not an online one.
Van anyone suggest another way to do this?
$(document).ready(function() {
if (typeof(localStorage) === 'undefined' ) {
alert('Your browser does not support HTML5 localStorage. Try upgrading.');
} else {
$("#return_form2").submit(function(){//load the items
getItems();
});
}
});
var getItems = function() {
var timeLog, logLength, i;
i = 0;
logLength = localStorage.length-1; //how many items are in the database starting with zero
timeLog = '';
// loop through each item in the database
for (i = 0; i <= logLength; i++) {
var itemKey, value, values, firstname, password, email;
//variables for the key and values
itemKey = localStorage.key(i);
value = localStorage.getItem(itemKey);
values = JSON.parse(value);
firstname = values.fname;
password = values.pass;
email = values.email;
course = values.class;
var tt = course;
var un = document.return_form2.username.value;
var pw = document.return_form2.password.value;
var web = "Web Systems Development";
if ((un == firstname) && (pw == password) && (tt == web)){
window.location.href = "AppMenu.html";
return false;
}
else {
alert ("Incorrect Password");
}
}}
I'm not sure that ((un == firstname) && (pw == password) && (tt == web)) is true, anyway, the next line worked for me
window.location="AppMenu.html";
Also you don't have to return false
I need some help on an assignment that I need to do. Basically the question is a number guessing game. We're assigned a number in the interval [0,1023] based on our student number and we have 11 guesses to get the right number. I know I have to use a binary search to get the number, my only problem is connecting to the server and getting a result.
We're given this:
A sample request looks as follows:
http://142.132.145.50/A3Server/NumberGuess?snum=1234567&callback=processResult&guess=800
And also given that the request returns the following parameters:
1: A code to determine if your guess is equal, less than or greater than the number
2: Message string
3: Number of guesses made by my application
This is what I've tried so far, just as a test to get the server request working. All I get in return is "object HTMLHeadingElement"
window.onload = function() {
newGuess();
}
function newGuess() {
var url = "http://142.132.145.50/A3Server/NumberGuess?snum=3057267&callback=processResult&guess=600";
var newScriptElement = document.createElement("script");
newScriptElement.setAttribute("src", url);
newScriptElement.setAttribute("id", "jsonp");
var oldScriptElement = document.getElementById("jsonp");
var head=document.getElementsByTagName("head")[0];
if (oldScriptElement == null) {
head.appendChild(newScriptElement);
} else {
head.replaceChild(newScriptElement, oldScriptElement);
}
}
function processResult(code,message,guesses) {
var code = document.getElementById("code");
var message = document.getElementById("message");
var guesses = document.getElementById("guesses");
code.innerHTML = code;
message.innerHTML = message;
guesses.innerHTML = guesses;
}
EDIT: Current state of my code.
window.onload = function() {
min = 0;
max = 1023;
mid = 0;
setInterval(newGuess,1000);
};
function newGuess() {
mid = Math.floor((max-min)/2);
var url = "http://142.132.145.50/A3Server/NumberGuess?snum=3057267&callback=processResult&guess="+mid;
var newScriptElement = document.createElement("script");
newScriptElement.setAttribute("src", url);
newScriptElement.setAttribute("id", "jsonp");
var oldScriptElement = document.getElementById("jsonp");
var head=document.getElementsByTagName("head")[0];
if (oldScriptElement == null) {
head.appendChild(newScriptElement);
} else {
head.replaceChild(newScriptElement, oldScriptElement);
}
}
function processResult(codeJ,messageJ,guessesJ) {
code = document.getElementById("code");
message = document.getElementById("message");
guesses = document.getElementById("guesses");
code.innerHTML = codeJ;
message.innerHTML = messageJ;
guesses.innerHTML = guessesJ;
if(codeJ == 0){
return;
}else if(codeJ == -1){
min = mid + 1;
}else if(codeJ == 1){
max = mid -1;
}
console.log(mid);
}
Check your variable-names. You are overwriting the function-patameters.
Something like
code.innerHTML = code;
message.innerHTML = message;
guesses.innerHTML = guesses;
just CAN'T work, you should see the problem yourself...