How to have my input value appear in all my html pages? - javascript

I am storing the username and password in an array(datas),,then after registering and logging in, I am only able to have the username appear in the login page.. How can i make the username appear in all of my html pages?Like storing it in a session variable so i could have the username in all of my other pages. Thank you!
<script>
let datas = [];
const addData = (ev) => {
ev.preventDefault();
let data = {
username: document.getElementById('rusername').value,
password: document.getElementById('rpassword').value
}
datas.push(data);
document.forms[0].reset();
}
document.addEventListener('DOMContentLoaded', () => {
document.getElementById('register_button').addEventListener('click', addData);
});
function isUserValid(e) {
e.preventDefault();
var username = document.getElementById('lusername').value;
var password = document.getElementById('lpassword').value;
var found_user = datas.find(d => d.username === username && d.password === password);
if (found_user) {
document.getElementsByClassName('loguser')[0].innerHTML = found_user.username;
}
}
document.getElementById("login_button").addEventListener("click", isUserValid);
</script>
<body>
<div class="loguser">
User
</div>
<div class="wrapper">
<div class="login_box">
<div class="login_header">
<img src="images/alimama.png" alt=""> <br> Login or Register!
</div>
<div id="login">
<form action="" method="POST">
<input id="lusername" type="text" name="lusername" placeholder="Username" required>
<br>
<input id="lpassword" type="password" name="lpassword" placeholder="Password">
<br>
<input type="submit" id="login_button" name="login_button" value="Login">
<br>
Need an account? Register here!
</form>
</div>
<div id="register">
<form action="" method="POST">
<input id="rusername" type="text" name="rusername" placeholder="Username" required>
<br>
<input id="rpassword" type="password" name="rpassword" placeholder="Password" required>
<br>
<input id="register_button" type="submit" name="register_button" value="Register">
<br>
Already have an account? Sign in here!
</form>
</div>
</div>
</body>

You can use your browser's localstorage to store the values and retrieve them on other pages. Another option would be to use cookies, but I believe this would be a little more complicated.
https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
Here's the documentation that talks a little more about. I think this will help you =)
An important point is that this will be saved in the user's browser, if you need this data, I recommend using a database

Use localStorage, is really simple. To set the value use this:
window.localStorage.setItem('actualUserName', document.getElementById('lusername').value);
And to retrieve the value use this:
window.localStorage.getItem('actualUserName');
More info: https://developer.mozilla.org/es/docs/Web/API/Window/localStorage

Related

Submit button taking me to link that states HTTP ERROR 405. How do I prevent this, so i can allow it to work the way it is intended to?

I'm still learning, so if there's any help, or the answer is really trivial like something I need to put before hand, an explanation of the reason why this is happening would be greatly appreciated!
This has been a problem ever since I have started using it for weekend projects. Whenever I make a button, for example one that I have been trying to use is
<button type="submit" id="btn" onclick="validate()">login</button>
However, when I click on the button, instead of showing me what its supposed to show, it just states this on a gray page.
This page isn’t working
If the problem continues, contact the site owner.
HTTP ERROR 405
HTML
<div class="wrapper">
<form class="box" method="post">
<h3>login</h3>
<div class="username">
<input type="text" placeholder="enter username" id="username" name="usernmame" value="">
</div>
<div class="password">
<input type="password" placeholder="enter password" id="password"">
</div>
<button type="submit" id="btn" onclick="validate()">login</button>
</form>
</div>
JS
//I do understand that this is not a good way of setting up a username and password ,since anyone can easily get it. Ive been just doing this as a weekend project, i just want it to show an alert if it works or not
function validate(){
let username = document.getElementById('username');
value;
let password=document.getElementById('password');
value;
if(username =='please' && password == 'work')
{
alert('finally');
} else{
alert("NOOOO")
}
}
I have tried to see if it was a problem with my js, but nothing seems to change, so that is why im starting to suspect that it its the button thats causin the problem
Firstly its not
document.getElementById('password');
value;
its
document.getElementById('password').value;
Secondly, there is no action property present I'll suggest removing the entire form tags
<div class="wrapper">
<h3>login</h3>
<div class="username">
<input type="text" placeholder="enter username" id="username" name="usernmame" value="">
</div>
<div class="password">
<input type="password" placeholder="enter password" id="password"">
</div>
<button type=" submit" id="btn" onclick="validate()">login</button>
</div>
<script>
function validate() {
let username = document.getElementById('username').value;
let password = document.getElementById('password').value;
if (username == 'please' && password == 'work') {
alert('finally');
} else {
alert("NOOOO")
}
}
</script>
on your for, you are using attibute method="post" which has alternative of method="get" which being sent using URLs you are using method="post" which has a missing attribute action="/action_page.php" that will process you're page.
Like this
<form class="box" action="/action_page.php" method="post">
since you don't have action attribute, and has method="post", the post is being sent to the same page you are sending and without receiving it properly like in php.
$username = $_POST['username'];
If you still want to continue using javascript at test it, remove at post method, and remove the type="submit" on your button as it behaves on submitting if you just want to test using javascript.
Here is your final script.
HTML
<form class="box">
<h3>login</h3>
<div class="username">
<input type="text" placeholder="enter username" id="username" name="usernmame" value="">
</div>
<div class="password">
<input type="password" placeholder="enter password" id="password"">
</div>
<button id="btn" onclick="validate()">login</button>
</form>
</div>
JS
function validate(){
let username = document.getElementById('username').value;
let password=document.getElementById('password').value;
if(username =='please' && password == 'work')
{
alert('finally');
} else{
alert("NOOOO")
}
}

form validation + json parse

so i got a contacts.json file in which i'll store what i will submit from my form in the contact page. The 'storing' works well, just i want to add a validation to it, and only after that validation to be able to send and store those so called contacts. here's what i have:
app.js:
app.post('/contact', function(req, res) {
console.log(req.body);
const contacts_path = __dirname + '/privat/contacts.json';
const contactDataJson = fs.readFileSync(contacts_path);
const json_data = JSON.parse(contactDataJson);
const contact = {
email: req.body.email,
content: req.body.content
}
json_data["contacts"].push(contact);
fs.writeFileSync(contacts_path, JSON.stringify(json_data));
res.sendFile(__dirname + '/static/contact.html');
});
html:
<div id="container">
<div class="form-wrap">
<form method="POST" action="/contact">
<h1>Share your thoughts!</h1>
<p>Email</p>
<input id="email" name="email" placeholder="Type here your email" type="text"><br><br>
<p>Tell us what you think about us!</p>
<textarea id="content" name="content" class="contactarea" rows="10" placeholder="What would you like to talk about?"></textarea><br><br>
<button type="submit" class="btn">
<i class="fas fa-sign-in-alt"></i>submit
</button>
</form>
</div>
</div>
The validation you want to do is on the client side, so you need to perform it before the form is posted to your backend service (app.js). In order to do so, you can add a handler to the submit action, which would invoke the validation method and then submit the form. Something like:
<div id="container">
<div class="form-wrap">
<form id="myForm" method="POST" action="/contact">
<h1>Share your thoughts!</h1>
<p>Email</p>
<input id="email" name="email" placeholder="Type here your email" type="text"><br><br>
<p>Tell us what you think about us!</p>
<textarea id="content" name="content" class="contactarea" rows="10" placeholder="What would you like to talk about?"></textarea><br><br>
<button class="btn" id="submitBtn"> <i class="fas fa-sign-in-alt"></i>submit</button>
</form>
<script>
var button = document.getElementById('submitBtn');
button.addEventListener('click', function(e) {
// prevents the form from submitting
e.preventDefault();
emailValid();
// other validations you want to add
var form = document.findElementById('myForm');
form.submit();
});
</script>
If you want to validate the email address in your HTML, you can do this:
<input id="email" name="email" onkeyup="emailValid()" placeholder="Type here your email" type="text">
<script>
function emailValid() {
var emailaddr = document.getElementById("email").value
if (emailaddr.includes("#gmail.com") !== true) {
emailaddr.value = "Invalid Email Address";
return false;
else {
return true;
}
}
</script>
To validate the email on submission, just call the emailValid() function in your script that runs on submission.

Signup page button isn't redirecting me to another page

<body>
<h1 style="color:red;">SIGN UP</h1>
<p style="color:blue;">Please fill in this form to create an account.</p>
<label for="Email">Email:</label>
<input type="text" id="Email" name="Email"><br><br>
<label for="password">password:</label>
<input type="text" id="password" name="password"><br><br>
<label for="repeatpassword">repeatpassword:</label>
<input type="text" id="repeatpassword" name="repeatpassword"><br><br>
<button onclick="email" >SIGNUP!</button>
<script>
var email = document.getElementById("Email").value;
function email(){
if(document.getElementById("password").value===document.getElementById("repeatpassword").value && email.include("#")== true){
location.href = "question2.html";
}
}
</script>
</body>
</html>
I want to redirect to another html page when clicking on signup button and email input field contains "#" and password input field value is same as repeatpassword but I don't know what is wrong with my code
Check out with window.location.href in the script function to redirect.
for more reference look out https://www.w3schools.com/js/js_window_location.asp
Button onclick="email()" parenthesis is required because you are calling a function on a button click.
Function can't access a variable declared outside the function. So declare that email var inside the function scope.
It's not email.include() function it's includes(). "s" was missing. Ref -
https://www.w3schools.com/jsref/jsref_includes.asp
function email(){
var email = document.getElementById("Email").value;
if(document.getElementById("password").value===document.getElementById("repeatpassword").value && email.includes("#")== true){
console.log("Working");
}
else{
console.log("Not working");
}
}
<h1 style="color:red;">SIGN UP</h1>
<p style="color:blue;">Please fill in this form to create an account.</p>
<label for="Email">Email:</label>
<input type="text" id="Email" name="Email"><br><br>
<label for="password">password:</label>
<input type="text" id="password" name="password"><br><br>
<label for="repeatpassword">repeatpassword:</label>
<input type="text" id="repeatpassword" name="repeatpassword"><br><br>
<button onclick="email()" >SIGNUP!</button>

window.location.replace not working with jquery

I am having a little problem here for some reason. I have another page with almost the exact same code and it redirects the user to the page that I want them to go to. For some reason this one does not. I have tried commenting out the if statement and everything down to the point of just having the window.location.replace with the click action and still no luck.
JS
$(document).ready(() => {
$("#login-button").click(() =>{
if($("#pwd").val() === 'pass' && $("#username").val() === 'taylor') {
alert("Welcome: " + $("#username").val());
window.location.replace('../index.html');
} else {
alert("You have the wrong password and username");
}
});
});
HTML
<form id="login-form">
<div class="form-group">
<label for="username">Username:</label>
<input type="text" class="form-control" id="username">
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd">
</div>
<div class="checkbox">
<label><input type="checkbox"> Remember me</label>
</div>
<button id="login-button" class="btn btn-danger">Login</button>
</form>
You're mistaking what location.replace() is used for. To redirect, use location.href instead.
window.location.href = '../index.html';
The Location.replace() method replaces the current resource with the one at the provided URL. The difference from the assign() method is that after using replace() the current page will not be saved in session History, meaning the user won't be able to use the back button to navigate to it.
You also need to prevent the form submit. This is causing the page to be posted back to itself. Add the following inside your form submit event handler.
e.preventDefault();
You just need to stop the default form submit
html
<form id="login-form">
<div class="form-group">
<label for="username">Username:</label>
<input type="text" class="form-control" id="username">
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd">
</div>
<div class="checkbox">
<label>
<input type="checkbox"> Remember me</label>
</div>
<button id="login-button" class="btn btn-danger">Login</button>
</form>
jQuery
$(function() {
$("#login-button").click((e) {
if ($("#pwd").val() === 'pass' && $("#username").val() === 'taylor') {
alert("Welcome: " + $("#username").val());
window.location.href('../index.html');
e.preventDefault();
} else {
alert("You have the wrong password and username");
e.preventDefault();
}
});
});

Issue with javascript retrieve form data for url

I am kind of new to javascript however I have created a submit form that I want to redirect me to a url based on form input. Here is my current code...
The issue I'm running into however is that the form is sending me the initial value rather than the updated form value (It is using "whatevs" no matter what).
HTML
<form id="Search-Form" onClick="genURL()"><label>Value: </label>
<input type="text" id="search" placeholder="Enter Value"></input>
<div id="search-buttons">
<input id="searchSubmit" value="whatevs" type="submit" tabindex="1" />
</div>
</form>
Javascript
function genURL() {
var searchSubmit = document.getElementById("searchSubmit").value;
window.location = "randomsite/view" + searchSubmit;
}
Add return and use onsubmit:
<form id="Search-Form" onsubmit="return genURL()"><label>Value: </label>
<input type="text" id="search" placeholder="Enter Value"></input>
<div id="search-buttons">
<input id="searchSubmit" value="whatevs" type="submit" tabindex="1" />
</div>
</form>
Revise function like so:
function genURL()
{
location.href = "randomsite/view" + document.getElementById("search").value;
return false;
}
If you were to use onclick, it would go on the button, not the form.

Categories