In the script below, I try to record in the bowser the name of the users who connect to my application. If it is the first time that a user connects, when he presses the "submit" button to connect to the application I want a message "Welcome" + name + "!
If the user has already connected (his name is already registered in the localStorage), when he presses the submit button, I want a "Welcome back" + name + "!
Thank you for the comments below, I tried to take them into account. When I run the updated code below, only welcome appear on the message. The name of the user is not included on the message. How can I modify my code to correct this problem?
Thank you in advance for your advice.
JS script:
let myButton = document.getElementById ("myButton");
let myText = document.getElementById ("username");
function store() {
let n = 0;
while (localStorage.getItem("username" + n)) {
n++;
}
localStorage.setItem("username" + n, myText.value);
}
function welcomeUsername(){
let resultMessage = "Welcome "
let n = 0;
while (n) {
let user = localStorage.getItem("username" + n);
if(myText.value != user){
resultMessage += myText.value + "!";
break;
} else {
resultMessage += "back" + myText.value + "!";n++;
}
}
alert(resultMessage);
}
HTML Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login Page</title>
</head>
<body>
<br />
<br />
<div class ="login_card"></div>
<div class = "log_head">
<h1>Login</h1>
</div>
<div class = "log_body">
<br />
<label for="uname"><b>Please enter your username below and click on submit:</b></label> <br>
<input type="text" value = "Enter username" onfocus = 'this.value =""' id = "username"> <br>
<br> <br>
<input type="button" onClick="welcomeUsername();location.href ='/index';" value = "Submit" id = "myButton">
</div>
</div>
this part of your code has problem let value = localStorage.getItem("username"). you cant get any value from your localstorage since you set them 'username'+n, that;s why your if statement always run.
can you try this: while (n) {let user = localStorage.getItem("username" + n); if (myText.value == user) {resultMessage += myText.value; break; } else {resultMessage += "back" + myText.value + "!"; n++; }}
Try this.
const btn = document.getElementById('myButton');
// get a welcome message
const welcomeText = (name) => {
// store the name as an array type, initialize if it does not exist
let names = localStorage.getItem('usernames');
names = names == null ? [] : names;
// check if the name exists and decide the welcome message according to the result
if (names.includes(name)) {
return `Welcome back ${name}`;
} else {
// update storage information
names.push(name);
localStorage.setItem('usernames', names);
return `Welcome ${name}`;
}
};
// send name and call method
const submit = () => {
const name = document.getElementById('username').value;
alert(welcomeText(name));
};
btn.addEventListener('click', submit);
Related
const newFirst = document.getElementById("changeFName");
const newLast = document.getElementById("changeLName");
const newMail = document.getElementById("changeMail");
const newPass = document.getElementById("changePass");
const saveMe = document.getElementById("btn-save");
newData = (e) => { //mouseclick
e.preventDefault();
const first_name = changeFName.value;
const last_name = changeLName.value;
const e_mail = changeMail.value;
const pass_word = changePass.value;
let user_data = {
newFirst: first_name,
newLast: last_name,
newMail: e_mail,
newPass: pass_word,
}
let clientsArr = JSON.parse(localStorage.getItem('users'));
clientsArr.push(user_data);
localStorage.setItem("users", JSON.stringify(clientsArr));
}
saveMe.addEventListener("click", newData);
I've been trying to replace stored data of user using my "signup form" inside the local storage but:
the data is not being replace it's just creating new user (name,lastname,email,password)
I recycled my signup code hoping that this will work,
I have also login form that allowing each user to store to do list without changing the to do list of each other.
this is a TO-DO-LIST project from online course.
You try use below code
Reference: enter link description herehttps://www.w3schools.com/jsref/prop_win_localstorage.asp
<!DOCTYPE html>
<html>
<head>
<script>
function clickCounter() {
if(typeof(Storage) !== "undefined") {
if (localStorage.clickcount) {
localStorage.clickcount = 2;
localStorage.clickcount = Number(localStorage.clickcount)+1;
} else {
localStorage.clickcount = 1;
}
document.getElementById("result").innerHTML = "You have clicked the button " + localStorage.clickcount + " time(s).";
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support web storage...";
}
}
</script>
</head>
<body>
<p><button onclick="clickCounter()" type="button">Click me!</button></p>
<div id="result"></div>
<p>Click the button to see the counter increase.</p>
<p>Close the browser tab (or window), and try again, and the counter will continue to count (is not reset).</p>
</body>
</html>
you need a unique field to recognize user like id, email.
using this code you can update your existing user data (without email)
const newEmail = document.getElementById("email");
const newName = document.getElementById("name");
const frm = document.getElementById("frm");
frm.addEventListener("submit", e => {
e.preventDefault();
const email = newEmail.value;
const name = newName.value;
const userData = { email, name };
const storage = JSON.parse(localStorage.getItem("users"));
if (!storage) {
localStorage.setItem("users", JSON.stringify([userData]));
} else {
const userIndex = storage.findIndex(el => el.email === email);
if (userIndex>=0) {
storage[userIndex] = userData;
localStorage.setItem("users", JSON.stringify(storage));
} else {
storage.push(userData);
localStorage.setItem("users", JSON.stringify(storage));
}
}
});
<form id="frm">
email: <input id="email" type="text" />
name: <input id="name" type="text" />
<button type="submit">save me</button>
</form>
I have a small issues with my code.
Basically, I have a form in my index.html file:
The form from page 1 is the following:
<form method="get" name="basicSearch" id = "basicSearch" action="page2.html">
<input name="location" type="text" class="BasicSearch" id="searchInput" placeholder="Location">
<button type= "submit" class="BasicSearch" id="searchBtn" placeholder="Search"></button>
</form>
For this form, I want to use OpenWeatherMap API in order to get some weather data. My problem is the following:
I want to get what the user inputs in the form, which I think I can get by using, for example:
var searchInput = document.getElementById("searchInput");
In this variable I can store the location.
And this variable, I want to append to the link that does fetch the data from the API, in the javascript code.
When the user inputs, for example: New York, and press Search, the form action should redirect him to page2.html, where there I can show the weather data.
How can I show that weather data in the page2, with the location input from page1? I tried many times but no luck.
Some Javascript code down below:
let units = 'metric';
let searchMethod = 'q';
let searchButton = document.getElementById("searchBtn");
let searchInput = document.getElementById("searchInput");
if (searchButton) {
searchButton.addEventListener('click', () => {
let searchTerm = searchInput.value;
if (searchTerm)
searchWeather(searchTerm);
});
}
function searchWeather(searchTerm) {
fetch(`http://api.openweathermap.org/data/2.5/weather?${searchMethod}=${searchTerm}&APPID=${appId}&units=${units}`).then(result => {
return result.json();
}).then(result => {
init(result);
})
}
function init(resultFromServer){
let weatherDescriptionHeader = document.getElementById('weatherDescriptionHeader');
let temperatureElement = document.getElementById('temperature');
let humidityElement = document.getElementById('humidity');
let windSpeedElement = document.getElementById('windSpeed');
let cityHeader = document.getElementById('cityHeader');
let weatherIcon = document.getElementById('documentIconImg');
weatherIcon.src = 'http://openweathermap.org/img/w/' + resultFromServer.weather[0].icon + '.png';
let resultDescription = resultFromServer.weather[0].description;
weatherDescriptionHeader.innerText = resultDescription.charAt(0).toUpperCase() + resultDescription.slice(1);
temperatureElement.innerHTML = Math.floor(resultFromServer.main.temp) + '°' + " C";
windSpeedElement.innerHTML = 'Winds at ' + Math.floor(resultFromServer.wind.speed) + ' mph';
cityHeader.innerHTML = resultFromServer.name;
humidityElement.innerHTML = 'Humidity levels at ' + resultFromServer.main.humidity + '%';
}
That is some javascript code which should get the weather data.
Then, in page2, I have the following in HTML:
<div id = "weatherContainer">
<div id = "weatherDescription">
<h1 id = "cityHeader"></h1>
<div id= "weatherMain">
<div id = "temperature"></div>
<div id = "weatherDescriptionHeader"></div>
<div><img id = "documentIconImg"></div>
</div>
<hr>
<div id = "windSpeed" class = "bottom-details"></div>
<div id = "humidity" class = "bottom-details">></div>
</div>
</div>
I expected to have the weather data in page2, where the divs are.
Can somebody give me an advice, please?
Thank you!
Since the form in page1 doesn't exist in page 2, remove
let searchButton = document.getElementById("searchBtn");
let searchInput = document.getElementById("searchInput");
if (searchButton) {
searchButton.addEventListener('click', () => {
let searchTerm = searchInput.value;
if (searchTerm)
searchWeather(searchTerm);
});
}
instead put
ley searchTerm = new URLSearchParams(location.search).get('location');
searchWeather(searchTerm);
Explanation
When the page 1 form is submitted, it will load page2 like
page2.html?location=xxxx
where xxxx is the value of the <input name='location' ...
location.search will be ?location=xxxx
URLSearchParams makes dealing with these (when you have more than one especially) easier than the old method of splitting/decoding/jumping through hoops
We can simply just submit the form and get the current form input from url on page2.html
<form method="get" name="basicSearch" id = "basicSearch" action="page2.html">
<input name="location" type="text" class="BasicSearch" id="searchInput" placeholder="Location">
<button type= "submit" class="BasicSearch" id="searchBtn" placeholder="Search">Search</button>
</form>
And on the load of page2.html (before your ajax call), we can get the 'searchInput' (location) from URL by following:
<script>
let params = (new URL(document.location)).searchParams;
var searchInput= params.get('location');
</script>
Now, we can use 'searchInput' param for your api call and fetch the result.
i want to build mini webchat - When view site i set show 5 messages and if view more, you can click button. All things are fine but when i remove 1 node, firebase auto add last node into, how can i prevent it?
Ex: I have node A,B,C,D,E,F,G. I had loaded list C,D,E,F,G but when i delete 1 in all, it auto add B into list.
<div id="messgesDiv">
<center><h3>Message</h3></center>
</div>
<div style="margin-top: 20px;">
<input type="text" id="nameInput" placeholder="Name">
<input type="text" id="messageInput" placeholder="Message" data-id="">
<input type="text" id="idproject" placeholder="ID Project">
</div>
<button id="delete">Delete Test</button>
<button id="edit">Edit</button>
<button id="loadmore">Load more</button>
<button id="showlastkey">Show last key</button>
My javascript
$('#loadmore').click(function() {
i = 0; old = first;
myDataRef.orderByKey().endAt(first).limitToLast(6).on('child_added', function (snapshot){
if( i == 0)
first = snapshot.key();
var message = snapshot.val();
if(snapshot.key() != old)
displayChatMessage(message.name, message.text, message.idproject, 'old');
i++;
console.log('myDataRef.orderByKey().endAt(first).limitToLast(6)');
});
});
$("#messageInput").keypress(function (e){
if(e.keyCode == 13){ //Enter
var name = $("#nameInput").val();
var text = $("#messageInput").val();
var idproject = $("#idproject").val();
if($("#messageInput").data("id")=='')
{
myDataRef.push({name: name, text: text, idproject: idproject});
}
else
{
myDataRef.child(key).update({name: name, text: text, idproject: idproject});
$('#messageInput').attr('data-id', '');
}
$("#messageInput").val("");
}
});
myDataRef.limitToLast(5).on('child_added', function (snapshot){
if( i == 0)
first = snapshot.key();
var message = snapshot.val();
displayChatMessage(snapshot.key(), message.name, message.text, message.idproject, 'new');
i++;
console.log(snapshot.key());
console.log(' myDataRef.limitToLast(5)');
});
function displayChatMessage(key, name, text, idproject, status){
//console.log(name + " -- " + text + " -- " +idproject);
if( status == 'new')
{
$('<div/>', { 'data-id': key , 'class' : 'test'}).text(text + " - ").prepend($('<em/>').text(name+": " )).append("IdProject: "+idproject).appendTo($("#messgesDiv"));
$("#messgesDiv")[0].scrollTop = $("#messgesDiv")[0].scrollHeight;
}
else
{
$('<div/>', { 'data-id': key , 'class' : 'test'}).text(text + " - ").prepend($('<em/>').text(name+": " )).append("IdProject: "+idproject).insertAfter($("center"));
$("#messgesDiv")[0].scrollTop = $("#messgesDiv")[0].scrollHeight;
}
}
$('#delete').click(function() {
myDataRef.child(key).remove();
$('#messgesDiv').filter('[data-id="'+key+'"]').remove();
});
Firebase limit queries act like a view on top of the data. So if you create a query for the 5 most recent messages, the Firebase client will ensure that you always have the 5 most recent messages.
Say you start with these messages:
message1
message2
message3
message4
message5
Now if you add a message6, you will get:
child_removed message1
child_added message6
So that your total local view becomes:
message2
message3
message4
message5
message6
Conversely when you remove message 6 again, you get these events:
child_removed message6
child_added message1 (before message2)
So that you can update the UI and end up with the correct list again.
There is no way to change this behavior of the API. So if you want to handle the situation differently, you will have to do this in your client-side code.
Your code currently only handles child_added. If you have add a handler for child_removed you'll see that you can easily keep the user interface in sync with the data.
Alternatively you can detect that the message is already in your UI by comparing the key of the message you're adding to the ones already present in the DOM:
function displayChatMessage(key, name, text, idproject, status){
var exists = $("div[data-id='" + key + "']").length;
if (status == 'new' && !exists) {
$('<div/>', { 'data-id': key , 'class' : 'test'}).text(text + " - ").prepend($('<em/>').text(name+": " )).append("IdProject: "+idproject).appendTo($("#messgesDiv"));
$("#messgesDiv")[0].scrollTop = $("#messgesDiv")[0].scrollHeight;
}
else {
$('<div/>', { 'data-id': key , 'class' : 'test'}).text(text + " - ").prepend($('<em/>').text(name+": " )).append("IdProject: "+idproject).insertAfter($("center"));
$("#messgesDiv")[0].scrollTop = $("#messgesDiv")[0].scrollHeight;
}
}
I am trying to take a user input value that is entered through an html input box, and have it as a value within my function (the negKeyword function in my code to be more specific). The problem that I think is happening is this input value is stored as a variable, so when the code is first stored in memory it is stored as "", since the user has not inputed anything yet. How do I get it so when the user inputs something it replaces blank or "" with what ever the user inputs?
What I basically want to happen next is the user will click a button, it will then compare what the user inputs to what the "negKeyword" function outputs and give a result on whether they match or not (this action is demonstrated in my booleanKeyword function in my code).
Here is my code.
var input = document.getElementById("input").value;
var arr = ['no', 'not', 'checked'];
var text = ''; //JS output variable.
var keyword = 'leak'; //Individual keyword.
function negKeyword() {
for (i = 0; i < arr.length; i++) {
if (text == input) { break; }
text = arr[i] + ' ' + keyword;
}
return text;
}
function booleanKeyword() {
if (input == negKeyword()) {
document.getElementById("result").style.color="green";
document.getElementById("result").innerHTML="Match";
} else {
document.getElementById("result").style.color="red";
document.getElementById("result").innerHTML="No Match";
}
}
document.getElementById("result2").innerHTML=keyword;
<label for="Full Negative Keyword">Negative Keyword</label> <input id="input" type="text" />
<div id="message">Result: <span id="result"></span></div>
<div id="message">Keyword: <span id="result2"></span></div>
<button id="test" onclick="booleanKeyword()">Click to Test</button>
You can retrieve the input's value again, by getting it and assigning to the same variable (but inside the function that is called after the button click).
var input = document.getElementById("input").value;
var arr = ['no', 'not', 'checked'];
var text = ''; //JS output variable.
var keyword = 'leak'; //Individual keyword.
function negKeyword() {
input = document.getElementById("input").value;
for (i = 0; i < arr.length; i++) {
if (text == input) { break; }
text = arr[i] + ' ' + keyword;
}
return text;
}
function booleanKeyword() {
input = document.getElementById("input").value;//The variable is reassigned, only after the click
if (input == negKeyword()) {
document.getElementById("result").style.color="green";
document.getElementById("result").innerHTML="Match";
} else {
document.getElementById("result").style.color="red";
document.getElementById("result").innerHTML="No Match";
}
}
document.getElementById("result2").innerHTML=keyword;
Edit: added the same code to negKeyword() function as it requires the input too.
It is not working because your variable input is always "". You have to assign new value to it each time the button is clicked. I just moved your code for input in BooleanKeyword() function. Now everything is working fine.
Everytime when something like this is not working, just try to log/alert values.
For example you could just alert(input + ' ' + negKeyword()); on top of booleanKeyword() function and you would see problem by yourself.
var input;
var arr = ['no', 'not', 'checked'];
var text = ''; //JS output variable.
var keyword = 'leak'; //Individual keyword.
function negKeyword() {
for (i = 0; i < arr.length; i++) {
if (text == input) { break; }
text = arr[i] + ' ' + keyword;
}
return text;
}
function booleanKeyword() {
input = document.getElementById("input").value;
if (input == negKeyword()) {
document.getElementById("result").style.color="green";
document.getElementById("result").innerHTML="Match";
} else {
document.getElementById("result").style.color="red";
document.getElementById("result").innerHTML="No Match";
}
}
document.getElementById("result2").innerHTML=keyword;
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<label for="Full Negative Keyword">Negative Keyword</label> <input id="input" type="text" />
<div id="message">Result: <span id="result"></span></div>
<div id="message">Keyword: <span id="result2"></span></div>
<button id="test" onclick="booleanKeyword()">Click to Test</button>
</html>
I am making a game in HTML and JavaScript. I have a button that the user presses to 'run' a command they entered. But, after they have 'connected' to an ip the button no longer works, there is no error in the console. How can I fix this?
var ip = ["192.168.1.1", "192.168.1.2", "192.168.1.3", "192.168.1.4"]
var gip;
var log;
var compname;
var svirus;
var connected = false;
function runcmd() {
var user = document.getElementById('code').value;
if (user == 'clear') {
l1.innerHTML = '';
l2.innerHTML = '';
l3.innerHTML = '';
l4.innerHTML = '';
l5.innerHTML = '';
l6.innerHTML = '';
l7.innerHTML = '';
l8.innerHTML = '';
l9.innerHTML = '';
l10.innerHTML = '';
};
if (user == 'connect') {
gip = prompt('Enter The Targets IP: ');
for (var key in ip) {
var user = document.getElementById('code').value;
if (ip[key] == gip) {
l1.innerHTML = 'Connecting to ' + gip;
l2.innerHTML = 'Connected to ' + gip;
connected = true;
grant.play()
l3.innerHTML = 'view bank';
l4.innerHTML = 'upload [virus]';
l5.innerHTML = 'disconnect [ip]';
var user = document.getElementById('code').value;
if (user == 'disconnect' + gip) {
connected = false;
l1.innerHTml = 'Disconnected Safely...';
};
if (user == 'view bank') {
var pwrd = Math.floor(Math.random() * 10000);
var nam = Math.floor(Math.random() * 10000);
alert(pwrd);
alert(nam);
var uname = 'user' + nam;
var user = prompt('Username: ');
var pass = prompt('Password: ');
if (user == uname && pass == pwrd) {
console.log('hello')
};
if (user == 'upload') {
svirus = prompt('Enter Virus: ');
for (var key in boughtviruses) {
if (boughtviruses[key] == svirus) {
l1.innerHTML = 'Uploading ' + svirus;
l2.innerHTML = 'Virus Uploaded';
}
else {
alert("You Don't Have This Virus!");
};
};
};
};
};
};
};
};
<span class="span" id="l1"></span><br />
<span class="span" id="l2"></span><br />
<span class="span" id="l3"></span><br />
<span class="span" id="l4"></span><br />
<span class="span" id="l5"></span><br />
<span class="span" id="l6"></span><br />
<span class="span" id="l7"></span><br />
<span class="span" id="l8"></span><br />
<span class="span" id="l9"></span><br />
<span class="span" id="l10"></span><br />
<span >C:\></span>
<input onclick="this.select()" id="code" class="inp" />
<button id="runcodeuser" onclick="runcmd()">Send Command</button>
You could create an event dispatcher. Every possible user input would be a separate event.
Separate the code to handle each event into different functions.
For example:
function user_clear () { ... }
function user_connect () { ... }
function user_bank () { ... }
function user_upload () { ... }
function dispatch_event (user)
{
switch (user)
{
case 'clear': user_clear (); break;
case 'connect': user_connect (); break;
case 'view bank': user_bank (); break;
case 'upload': user_upload (); break;
default: console.log ('dispatch_event: no such event: ' + user);
}
}
Then call it from runcmd():
function runcmd() {
var user = document.getElementById('code').value;
dispatch_event (user);
}
And also after running grant.play(): (inside user_connnect())
grant.play();
var user = document.getElementById('code').value;
dispatch_event (user);
Well, in your code only two "commands" are actually usable - clear and connect.
If the command, that is the value of the textbox, is connect, the browser will ask for the "targets IP". It then iterates through the IPs in the array declared at the top, and in each iteration again sets the variable user to the textbox value - but the textbox will still contain connect, and also the user-variable is already declared, so there's no need to user the var keyword again.
Because of this user == "view bank" for example will never evaluate to true. You'll have to restructure your code considerably for this to work as you want it to.
It would appear that your runcmd() function only has 3 blocks:
var user...
if (user=="clear") { ... }
if (user=="connect") { ... }
Everything else is in that last block/line. If user=="connect" is true, then the block executes, but user=="view bank", etc. will never be true.
There's no semicolon after grant.play() - and this function doesn't seem to be defined anywhere inside your code.
Also, for what it's worth, I do get an error message when running the snippet:
{
"message": "Script error.",
"filename": "",
"lineno": 0,
"colno": 0
}