localStorage undefined? - javascript

Im doing a website project in my first year in college and i need to get local storage working. All i need is to input information of my website form and then display the local storage in another form on antoher page. i had it working but i added extra inputs, i made sure my ids and names were correct but it still wont work. Heres a part of all 4 files. I need this as it is right now but for some reason it wont work. I cant use anything new.
!(http://i57.tinypic.com/9hkjfd.png)
<form action="readLocalStorage.html" method="post" name="form1" id="form1" onsubmit="return validateForm()">
<fieldset>
<legend>Sign Up</legend>
<label for="username">Create a Username</label>
<input type="text" placeholder="5 characters" name="username" id="username" required><br><br>
<form name="LSdata" id="LSdata" action="addContact.php" method="post">
<label>Username</label>
<input name="username" id="username" readonly /><br />
function writeLocalStorage() {
localStorage.username = document.form1.username.value;
}
function getLocalStorage() {
document.LSdata.username.value = localStorage.username;
}

It looks like your variables are mismatched. You are setting username but getting Username. In JavaScript, variables are case sensitive so username will not always equal Username, they are two different variables.
Using your functions:
function writeLocalStorage() {
localStorage.username = 'mike';
}
function getLocalStorage() {
console.log(localStorage.Username); // what you currently have, will return undefined
console.log(localStorage.username); // returns "mike"
}
// returns:
// undefined
// mike
getLocalStorage();

Related

functions that supposed to be executed on submit do not work

I'm setting up web page (sign in page) where the user supposed to fill his personal info (just like a regular sign in page) but, the main purpose here is to check whether the user submitted his data properly and if not he would be notified by an alert message. My problem is with the functions which for some reason sometimes works and sometimes do not work.
The code is not fully completed but I can't continue with basic errors such as mine
I tried to find the solution in Stack Overflow and lots of js tutorials. Tried find a missing ";" or any other basic mistake that a beginner can do.
function goSign() {
var src = "signinpage.html"
window.open(src);
}
function checkAge() {
const x = document.forms["ageForm"]["age"].value;
const regex = /^\d{2}$/;
if (!x.match(regex)) {
alert("Must input numbers not longer than 2 digits");
return false;
}
}
function checkUsern() {
const username = document.forms["userForm"]["username"].value;
const regex = /^[A-Za-z0-9]+$/;
alert(
return namelen);
var minlen = 10;
if (minlen > username.length) {
alert("Your username must have atleast 10 characters");
return false;
}
}
<h1>Signin</h1>
<p>Please fill your details as requested</p><br>
<form name="nameForm" action="" onsubmit="return checkName()" method="post">
Full Name:<br>
<input type="text" name="fullname" />
</form>
<form name="ageForm" action="" onsubmit="return checkAge()" method="post">
Age:<br>
<input type="text" name="age" /><br>
<input type="submit" value="Submit" />
</form>
<form name="userForm" action="" onsubmit="return checkUsern()" method="post">
Username:<br>
<input type="text" name="username" /><br>
</form>
The expected output from those functions is, let's say the user entered a 3 digit number in his Age so he should be alerted "Must input numbers not longer than 2 digits", but instead the input just disappears and nothing happens.
Same thing with username.
Note: my main goal to do only 1 submit button that checks all the user's input but i dont know how to do it so instead i just apply a function and a submit button for every user input to make sure that the functions work properly...
The issue lies within return checkName() in the onsubmit handler for your inputs
The handler expects a function, so you should be fine to just write onsubmit="checkName"

How can I make a search bar with an <input> button open a domain if entered?

I currently have this code for a custom DuckDuckGo search bar:
<form action="https://duckduckgo.com/" method="get" id="ddg-search">
<div class="div-block-4">
<input autofocus="true" class="text-field-3 hero-search-bar w-input" data-name="q" id="field-3" maxlength="256" name="q" placeholder="Search DuckDuckGo" type="text">
</div>
</form>
It automatically opens the URL https://duckduckgo.com/?q={{SEARCH}} when you enter text in the box and press the enter key.
How could I make this bar go to a domain if one is entered? Optimally, it wouldn't validate the domain, just if it sees a string in the pattern xxxx.* with no spaces, it would open that page in a new tab.
Thank you for any help!
One way to solve it is by capturing the submit event of the form, analyze the input value and when it is a domain, open a new window with the domain and cancel the submit by returning false. In case of not being a valid domain, let the form proceed as usual by returning true.
Your html:
<form action="https://duckduckgo.com/" method="get" onsubmit="return decideWhatToDo()" id="ddg-search">
<div class="div-block-4">
<input autofocus="true" class="text-field-3 hero-search-bar w-input" data-name="q" id="field-3" maxlength="256" name="q" placeholder="Search DuckDuckGo" type="text">
</div>
<input type="submit" />
</form>
Your javascript:
function decideWhatToDo() {
let inputValue = document.getElementById('field-3').value;
if (isDomain(inputValue)) {
// the form won't be sent and a new window will open requesting the domain
if (!startsWithProtocol(inputValue)) {
inputValue = 'http://' + inputValue;
}
window.open(inputValue, '_blank');
return false;
}
// Proceed to send the form as usual
return true;
}
function startsWithProtocol(value) {
return /^((https?|ftp|smtp):\/\/)/.test(value);
}
function isDomain(value) {
return /^((https?|ftp|smtp):\/\/)?(www.)?[a-z0-9]+\.[a-z]+(\/[a-zA-Z0-9#]+\/?)*$/.test(value);
}
So one way to handle it is to use an if condition and check the string against a RegExp that recognizes domain names.
Here's a nifty one you can use:
/[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9](?:\.[a-zA-Z]{2,})+/
I assume you don't need help getting the value from your text field or the actual redirection. However, if you needed more help, comment below and I'll post a more complete answer. The code below should help you get to where you want:
var domainRegExp = /[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9](?:\.[a-zA-Z]{2,})+/
var pass = domainRegExp.test('test.com')
var fail = domainRegExp.test('test')
console.log(pass, 'pass')
console.log(fail, 'fail')
So as you can see the value inside the 'pass' variable is true, and 'fail' is false.

angular put code from a form into a [POST]

I have
var body = {username:"ali", password:"p"};
this.http.post('http://localhost:27017/user/auth', body).subscribe(data =>
{console.log(data);});
How can I load up the variable body with some data-binding from a form? I'm just making a login - I have two fields, username and password that the user enters, and then that will go into the second .post() parameter.
html code
<input type="text" id="username" required [(ngModel)]="user.username">
<input type="password" id="password" required [(ngModel)]="user.password">
<button (click)="submit()">submit</button>
ts code
user={username:"", password:""};
submit(){
const body = this.user;
this.http.post('http://localhost:27017/user/auth', body).subscribe(data =>
{console.log(data);});
}
EDIT: You need of course to add test for the form for more information https://angular.io/guide/forms

HTML Form using Javascript did not verify instead changed the link

Code:
<h1>Login Form</h1>
<form onsubmit="loginUsingPassword(this.form.loginPassword.value);return false;">
Password : <input type="password" name="loginPassword" /> <input type="submit" value="Submit" />
</form>
<script>
//This is for verifying use.
function generateUserPassword(){
var passwordArray = [];
passwordArray[0]="198237645";
passwordArray[1]="infotalkong";
function loginUsingPassword(inputPassword){
for (int i; i<passwordArray.length; i++){
if (inputPassword=passwordArray[i]){
document.cookie="reportLogged=true;";
window.location.href="http://tool-box.weebly.com/report.html";
}
}
}
</script>
Result:
Input : 198237645
Output : The link changed to http://tool-box.weebly.com/report-login.html?loginPassword=198237645
What is the solution?
I am not quite sure of your requirement, but there are some points might be helpful for you,
Generally we use method post for such form submission, rather than the default one(get).
So you might want to to change the follow code
<form onsubmit="loginUsingPassword(this.form.loginPassword.value);return false;">
to the follow one
<form onsubmit="loginUsingPassword(this.form.loginPassword.value);return false;" method="post">
After you do the above change, the password will not be displayed in the URL as you mentioned, to avoid security issue.
By reading your code, I assume you would like to check whether the password inputed by user is the same as a list of predefined password in your code.
But you have the follow code there
if (inputPassword=passwordArray[i]){//This is a common bug to mistake === to = in if
If you would like to compare the variable inputPassword and your predefined passwords(passwordArray), you should use == or === rather than the assignment operation(=), so the code should be
if (inputPassword === passwordArray[i]){
Hope the above hints could help you on debug your code.
Here is a working version based on my understanding to your requirement, but actually you didn't specify your requirement...
<h1>Login Form</h1>
<form onsubmit="loginUsingPassword(document.forms['myForm']['loginPassword'].value);return false;" method="post" name="myForm">
Password : <input type="password" name="loginPassword" /> <input type="submit" value="Submit" />
</form>
<script>
//This is for verifying use.
var passwordArray = [];
function generateUserPassword(){
passwordArray[0]="198237645";
passwordArray[1]="infotalkong";
}
function loginUsingPassword(inputPassword) {
generateUserPassword();
var passwordCorrect = false;
for (i = 0; i< passwordArray.length; i++){
if (inputPassword === passwordArray[i]){
document.cookie="reportLogged=true;";
passwordCorrect = true;
window.location.href="http://tool-box.weebly.com/report.html";
}
}
if (passwordCorrect !== true){
alert("Wrong Password!");
return false;
}
}
</script>
Your form tag has no method attribute, so it defaults to GET. It has no action attribute, so it defaults to the page you're on. If you submit the form, it encodes the submitted values in the URL (how GET is designed to work) and you land on the same page. This is exactly the behavior you have specified.

Javascript mini validation script

I'm new to js. trying to create mini validation function which will check fields if they're empty or not.
What i wanna do is, to call func like that checkIfEmpty("fullname, email,..."), then inside function, check each field seperated by comma, collect empty fields to one array, and check at the end if this array is empty or not. Tried something like following func, but don't know all alternatives of php functions in js. Please help me to realize my idea..
function checkIfEmpty(fields)
{
var emptyFields=new Array();
fields=fields.split(',');
foreach(fields as field)
{
if (!field.val()) {
field.attr('class', 'invalid');
emptyFields[] = field;
}
}
if(emptyFields.length()==0){return true;}
else {return false;}
}
Seems like you want something like this:
$("input:text").each(function(i, field) {
if (!field.val()) {
field.addClass('invalid');
}
});
return ($("input.invald").length > 0); // return true if invalid fields
You could also set a class on each input that not suppose to be empty, then on form submission check each input that has this class.
$('#form_id').submit(function() {
$('.required').each(function() {
// if a input field that's required is empty
// we add the class '.invalid'
if(!$(this).val()) {
$(this).addClass('invalid');
}
});
// prevent the submission if number
// there is required fields still empty
return ($('input.invalid').length == 0);
});
This is an example form with one required field called email:
<form method="POST">
<input type="text" name="email" class="required" />
<input type="text" name="firstname" />
<input type="text" name="lastname" />
<input type="submit" value="SEND" />
</form>

Categories