Odd error in Javascript "if" statement - javascript

I have a really weird error in my code that I just cannot figure it out. Basically, I'm making a simple username save/recall form. I take in input from a user and save it into a localstorage of browser. After, when I try to access with the input from before, I would recall the item from the localstorage.
My if statement doesn't seem to work. I tried comparing items individually - I tried comparing "document.getElementById('userName')" with a random string and "localStorage.getItem('login_info')" vice versa. However, when I try to do
if (localStorage.getItem('login_info') === document.getElementById('userName'))
The code would never return true as an output.
any ideas?
Thanks!
<!DOCTYPE html>
<html>
<head>
<title>Try</title>
</head>
<body>
<p> Please type in your username and password </p>
<form id="register_form">
<input id="name1" type="text" placeholder="Name" value=""/>
<input id="rgstr_btn" type="submit" value="Register" onClick="store()"/>
</form>
<form name="login">
<input id="userName" type="text" placeholder="Enter Username" value=""/>
<input id="login_btn" type="submit" value="Login" onClick="check()"/>
<input type="reset" value="Cancel"/>
</form>
<script type="text/javascript">
var user_name = document.getElementById('name1');
function store(){
localStorage.setItem('login_info', user_name.value)
}
function check(){
var storedName = localStorage.getItem('login_info');
// entered data from the login form
var user_Name = document.getElementById('userName');
if (document.getElementById('userName') === localStorage.getItem('login_info')){
alert("Login Successful! Continuing to ..");
window.open("Us.html");
}
else{
alert("Login unsuccessful, please try again!");
}
}
</script>
<noscript> Please try a different browser! </noscript>
</body>
</html>

Use document.getElementById('userName').value to fetch value from input text.
var user_name = document.getElementById('name1');
function store(){
localStorage.setItem('login_info', user_name.value)
}
function check(){
var storedName = localStorage.getItem('login_info');
// entered data from the login form
var user_Name = document.getElementById('userName').value;
if (document.getElementById('userName').value == localStorage.getItem('login_info')){
alert("Login Successful! Continuing to ..");
window.open("Us.html");
}
else{
alert("Login unsuccessful, please try again!");
}
}

Like #DhavalSoni said, you need to use element.value to compare.
document.getElementById is only meant to return the DOM object and not its value. Try console.log(Document.getElementById('username')) to examine the returned object in Chrome debugger.

Related

How to verify the elements of a form in Javascript then Move to a PHP page?

I want to verify the inputs by javascrpit function perform() and move to a php page named i.php to save the datas in the databasse.
Here is the code:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form action="i.php" method="post">
<br>
Name <input type="text" name="name" id="name" >
<span id="err"></span>
</br>
<br>
Password <input type="Password" name="Password" id="password">
<span id="perr"></span>
</br>
<br>
Gender
<input type="radio" name="gender" id="gender" value="male">Male
<input type="radio" name="gender" id="gender" value="female">Female
</br>
<br>
Department <select name="department" id="department">
<option>------</option>
<option>ECE</option>
<option>BBA</option>
<option>ENG</option>
</select>
</br>
<br>
<button name="btn" type="button" id="btn" onclick="perform()" >Button</button>
<input type="submit" name="submit" value="Submit">
<input type="reset" name="reset" value="Clear">
</br>
</form>
<script type="text/javascript">
function perform()
{
var name = document.getElementById('name').value;
var pass = document.getElementById('password').value;
var dept = document.getElementById('department').value;
var gender = document.getElementsByName('gender');
var r =3;
if (name.length==0)
{
document.getElementById('err').innerHTML = "name not found";
r++;
}
if (pass.length<=6 || pass.length>=32 )
{
document.getElementById('perr').innerHTML = "password error";
r++;
}
if(r==3)
{
window.location= "i.php";
}
}
</script>
</body>
</html>*
In i.php page i used var_dump to see the datas whether it has been submitted or not. code of the i.php page:
<!Doctype html>
<html>
<head></head>
<body>
<?php
var_dump($_POST);
?>
</body>
</html>
But its showing arry(0) {}
looks like there nothing that has been submitted.
The issue is that you're redirecting with javascript, and losing the entire form and it's data by doing so.
When the form is valid, submit it rather than redirecting
function perform() {
var _name = document.getElementById('name').value;
var pass = document.getElementById('password').value;
var dept = document.getElementById('department').value;
var gender = document.getElementsByName('gender');
var valid = true;
if (_name.length === 0) {
document.getElementById('err').innerHTML = "name not found";
valid = false;
}
if (pass.length <= 6 || pass.length >= 32) {
document.getElementById('perr').innerHTML = "password error";
valid = false;
}
if (valid) {
document.querySelector('form').submit();
}
}
Note that name is not a good name for variables or form elements, as it already exists in window.name, and that a submit button can not be named submit as it overwrites the named form.submit() function
Another option would be to just remove all the javascript, and use HTML5 validation instead.
Use this code:
<form action="i.php" method="post" onsubmit="perform();">
And in javascript make these changes:
if(r!=3) {
alert('please complete the form';
return false;
}
Javascript doesn't send POST headers with window.location!
By using this code, you don't need to use a button, javascript perform() function runs when the submit button is clicked in the form.
If form values are entered truly, javascript perform() does not return and form submits; else, the function returns and prevents submitting the form.
The problem is you are not submitting the form you are just going to a different page with javascript without passing along any variables. so instead of doing
window.location= "i.php";
you should submit the form like so
document.getElementById("formId").submit();
so you should give the form the id formId
The problem is that you are merely redirecting to the i.php page without posting any data. Replace this line in your JS:
window.location = "i.php";
with this
document.getElementsByTagName('form')[0].submit();
This will find the form in your DOM and submit it along with the data that has been input, preserving the values for your action page.
You also need to rename your submit-button for this to work. Otherwise you will not be able to call the submit function on the form programmatically.
<input type="submit" name="submit-btn" value="Submit" />
should do the trick. However, I don't really see the point of the submit button in addition to your validation/submission button.
Full code sample of the solution here: https://jsfiddle.net/dwu96jqw/1/
by press btn you redirect only and your form dont submitted for transfer via _POST
you should change your code :
<form action="i.php" method="post" id ="form1">
and :
if(r==3)
{
form1.submit();
}
window.location will redirect you to the page, to preserve field values return it
if(r==3)
{
return true;
}

javascript password checker with confirmation dont work

Could anyone help me i have following issue with it when i put the wrong passwort it still gives no alert and opens the site.(the whole code isnt working and i dont know where the error is..) thank you for your help.
<!DOCTYPE html>
<html>
<head>
<title> passwort </title>
<script type="text/javascript">
function vergleiche(a, b) {
return (a == b) ? true : false;
}
function val(frm) {
if (vergleiche("passwort", frm.password.value){
alert("pw richtig");
}
else {
alert("pw falsch");
frm.password.select();
frm.password.focus;
}
if (frm.password.value == "") {
alert("enter password abla");
frm.password.focus();
return false;
}
if ((frm.password.value).length < 3) {
alert("dein pw sollte schon länger sein hö");
frm.password.focus();
return false;
}
if (frm.confirmpassword.value == "") {
alert("enter password");
return false;
}
if (frm.password.value != frm.confirmpassword.value) {
alert("passwoerter ungleich lan");
}
return true;
}
</script>
</head>
<body>
<h2> passwort validation</h2>
<form name="frm" method="POST" action="pw.php" onSubmit="">
Enter vorname:<input type="text" name="vorname"/>
Enter Password: <input type="password" name="password" placeholder="Enter Password"/><br/>
<br/>
Confirm Password: <input type="password" name="confirmpassword" placeholder="Re-enter Password"/>
<br/>
<input type="submit" value="Submit" onclick=""/>
<input type="reset" value="Reset"/>
</form>
</body>
</html>
As Rax Weber said, you are not even calling your function.
You should not pass your form this way.
I think it's better to do something like this
<input type="submit" value="Submit" onclick="val()" />
And in val function. (Because your form don't have an ID....)
frm = document.getElementsByName("frm")[0];
The line "if(vergleiche("passwort",frm.password.value) {" is incorrect, you are missing one ")"
if(vergleiche("passwort",frm.password.value)) {
Proceeding like this, your function should work. However, I would recommand that you translate your code in english so everyone can understand, and you should also use some IDE like Eclipse or at least Notepad++ to indent your code properly.
Using those tools will make you do less syntax errors.

.HTML File has Password in URL [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I usually code in Java, but I knew a little HTML, so I decided I would learn more. My problem is that I have a password field and a submit button. When I hit the button, it checks to see if the password is right, and then asks you what your name is. It then changes a text field to say You got it right, NAME. The thing is, when you hit submit, the code submitted is added to the URL, so if you type password as the password, ?password is added on to the URL. That is fine with me, but since the URL is changed, the page reloads, making the text field go back to normal. I am using Google Chrome. Is there anyway around this, or is it because I am running a .HTML file, not going to a website?
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<title>Ryan Club Homepage</title>
<script>
function codeEnter(){
var s = document.getElementById("in").value;
var correct = "lolliPiper5";
if(s === correct){
var name = prompt("What is your name");
document.getElementById("cde").innerHTML = "You got the password right!, " + name;
}
}
</script>
</head>
<body style="font-family:'Myriad Pro' ">
<form onsubmit="codeEnter();">
<input type="password" name="code" id="in">
<br />
<input type="submit" value="Ready!">
</form>
</body>
</html>
Thank you!
You need to use JavaScript / jQuery to prevent the form from submitting. I am using jQuery 2.1.1.
For password field let's assume it 123 for now.
The e.preventDefault() method stops the default action of an element from happening. Here it stops the submit button to submit the form to URL specified in form's action attribute.
$(document).ready(function(){
$("#name_container").hide();
$('#submit').on("click",function(e){
e.preventDefault();
$password = $('#password').val();
if($password == '123'){
$("#password_container").hide();
$("#name_container").show();
$("#result").html("");
}
else{
$("#result").html("Password is incorrect.");
}
$name = $("#name").val();
if($name != '' && $name != null ){
$("#form").hide();
$("#result").html("You got it right, "+$name);
}
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="page.html" method="post" id="form">
<div id="password_container">
Password: <input type="password" id="password" />
</div>
<div id="name_container">
Name: <input type="text" id="name" />
</div>
<input type="submit" id="submit">
</form>
<div id="result">
</div>
(Updated)
Here you go:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body style="font-family:'Myriad Pro' ">
<form id="form" method="post" action="#">
Password:
<input type="password" name="code" id="in">
<br />
<input type="submit" value="Ready!" id="submit">
</form>
<div class="ps"></div>
<script>
$(document).ready(function () {
$('#submit').on("click", function (e) {
e.preventDefault();
$password = $('#in').val();
if ($password == 'lolliPiper5') {
$name = prompt("Enter your name", "ACCESS GRANTED");
$(".ps").html("Welcome to the team, " + $name);
}
});
});
</script>
</body>
</html>
In your simplified (I hope) code you need at least set
<form onsubmit="return codeEnter()">
...
// and in the script
function codeEnter(){
var s = document.getElementById("in").value;
var correct = "lolliPiper5";
if(s === correct){
var name = prompt("What is your name");
document.getElementById("cde").innerHTML = "You got the password right!, " + name;
}
else return false; //do not submit
}
In the real world if you actually wanted to submit the password, hidden from the user you would change the form code to
<form onsubmit="codeEnter();" method="post">
By default the form submits data to the server via a GET request which causes the values to show in the url, thus this is usually only used for making queries such as page numbers (?page=num) etc (all insensitive data).
However, when you set method="post" the form sends data using a POST request which is invisible to the user and in some cases encrypted before sending and therefore much safer.
An example of a for using method="POST" can be found here

javascript onsubmit event for multiple functions check doesn't work

In mi validation form I have two input fields in order to write email and confirm it.
Before the submit informations, two confirms are needed:
1-email must seems an email,
2-email one must match the email two.
I can handle these statements each one using two separate javascript functions but i fail when I try to check them all in the onsubmit event attribute. If I write a correct email adress, the form reach the action destination, even if the confirm email doesn't match.
Looking around the web doesn't help me.
Here u are the code (html/javascript):
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<title>Email Validation</title>
<script type="text/javascript">
function isEmail(email, output) {
var regex = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
var email = document.getElementById(email).value;
if (regex.test(email)) {
return true;
} else {
document.getElementById(output).innerHTML = 'wrong email';
return false;
}
}
function compareEmail(email, emailToCompare, output){
var email = document.getElementById(email).value;
var emailToCompare = document.getElementById(emailToCompare).value;
if(emailToCompare == email){
document.getElementById(output).innerHTML = 'ok!';
return true;
}else{
document.getElementById(output).innerHTML = 'emails dont match!';
return false;
}
}
function check(){
return isEmail() && compareEmail();
}
</script>
</head>
<body>
<form action="file.php" method="post" onSubmit="return check()">
<p>Email</p>
<input type="text" name="email" maxlength="50" id="email">
<div id="email_result">
</div>
<br/>
<p>Confirm email</p>
<input type="text" onpaste="return false;" autocomplete="off" name="email" maxlength="50" id="confirm_email" onKeyUp="return compareEmail('email', 'confirm_email', 'confirm_email_result')">
<div id="confirm_email_result">
</div>
<input type="submit" name="submit" value="Register" onclick="return isEmail('email', 'email_result');">
</form>
</body>
The double control doesn't work with the follow script too:
function check(){
if (isEmail() && compareEmail()){
return true;
}else{
return false;
}
}
Nothing changes if I use:
onSubmit="return check()"
or
onSubmit="check()"
in the form event attribute.
You are missing the parameters in the function calls:
function check(){
return isEmail('email', 'email_result') && compareEmail('email', 'confirm_email', 'confirm_email_result');
}
Side note: You have declared variables in the functions with the same name as the parameters. It still works at it is, but the variables are not actually created but will overwrite the parameter values, so the code is a bit confusing.

How do you put a string variable in the confirm() function in Javascript/HTML?

I am trying to confirm with the user if the following string he or she is about to enter is correct but the confirmation box won't appear. Here is that segment of the code:
<html xmlns="http://www.w3.org/1999/html" xmlns="http://www.w3.org/1999/html">
<head>
<script>
function validateForm(){
var pkey = document.forms["createProductForm"]["pagekeyTF"].value;
var agree = confirm("Is this your product?\n\n ${pkey}");
if(agree) //Do something
else //Do something else
}
</script>
</head>
<body>
<form name="createProductForm" controller="actions" action="ImplementNewProduct" onsubmit="return validateForm()" method="post">
<g:textField id="productTF" name="productTF" value="My Product" />
<button id="createProductID" name="createButton" value="Create Product">Create Product</button>
</form>
</body>
</html>
Am I not allowed to pass in string variables in the confirmation function? Because if I take off the ${pkey} it works fine but it does not include the user's input and that is not what I am not trying to achieve. Any help? Thanks!
Edit it like this :
var pkey = document.forms["createPixelForm"]["pagekeyTF"].value;
var agree = confirm("Is this your product?\n\n " + pkey);

Categories

Resources