Correct statment but incorrect outcome - javascript

I was trying to make a simple sign in system(thats local). But, I keep getting the incorrect outcome and I'm quite confused. I'm 99% sure that my if statments are correct but it keeps alerting 'Not good'. I don't really have a idea why it does that because when I put 'abcd1' in the Username text field it still alerts 'Not good'.
HTML:
<!DOCTYPE html>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form id='form'>
<title>Sign Up #1</title>
<h3>Simple Signup system</h3>
<form>
<div>
<label>Username:</label>
<input type="text" name="text1" id = "username">
</div>
<div>
<label>Password:</label>
<input type="text" name="text2" id = "password">
<div>
<button type="button" id="subBtn">Sign Up!</button>
</form>
</body>
<script src="main.js"></script>
</html>
JS:
// /home/ceta123/Desktop/ab/Sedmi/index.html
var rUsername = document.getElementById('username').value;
var rPassword = document.getElementById('password').value;
// /main
window.onload = function() {
document.getElementById('subBtn').addEventListener('click', onSubmit);
}
function onSubmit() {
function onSubmit2() {
if (rUsername.includes(Number))
console.log('Good');
else {
alert('Not good!');
}
}
if(rUsername == 'string' || rUsername instanceof String)
{
console.log('Is not a string')
}
else
{
onSubmit2();
}
document.forms['form'].submit();
}

This line doesn't make much sense in JS:
if (rUsername.includes(Number))
If you mean to check if username includes digits, you can use a regex instead:
if(\/d+\.test(rUsername))
To check if a variable is a string:
if(typeof rUsername === 'string')
instead of:
if(rUsername == 'string' || rUsername instanceof String)
You need to get the username value on submit, not when page is first loaded.
So you need to include this line in your onSubmit() function:
var rUsername = document.getElementById('username').value;

Use
if (typeof rUsername === 'string' || rUsername instanceof String)
Break your code into pieces by alert or console technique to have better outcomes.

Related

Having error in sign up and sign in for blogging websites

First of all, I'm a beginner so, I don't know much but, I expect you would help me.
I've made a website for blogging where you sign up and it redirects you to the main page. Here it should tell me if I already signed up once.
I should get an alert if I have signed up before and it should check pass but, here I am not getting it like that. In fact, it redirects even if I have entered the wrong password for the username.
I don't know why this happens...
Signup.html :
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href= "blog.css">
<meta charset="UTF-8">
<title>Page title</title>
</head>
<body>
<div class="Title" align="center">
<br>
<hr>
<h1> InFinite Blogging</h1>
<hr>
<br>
</div>
</div>
<form id="form" action="signup.html" method="post">
<div class="signup">
<input type="text" id="username" placeholder="username">
<br>
<input type="password" id="password" placeholder="password" >
<button id="next" onclick="check()">sign up </button>
</div>
</form>
<script src="blog.js"></script>
</body>
</html>
Blog.js :
var avail = false;
localStorage.setItem(0, 'admin');
localStorage.setItem('admin', '12345678');
function check() {
var user = document.getElementById('username').value;
var pass = document.getElementById('password').value;
var max1 = Object.keys.length;
var max = Object.keys.length-1;
if( user == "" || user== null || pass ==""|| pass==null ) {
alert("enter your name and password, first.");
document.getElementById('username').focus;
document.getElementById('password').focus;
return false;
} else if(pass.length<8) {
alert("Password must contain 8 characters.");
document.getElementById('username').focus;
document.getElementById('password').focus;
return false;
} else {
for (i = 0; i <= max; i++) {
if (user == localStorage.getItem(i)) {
alert("it looks like you already have account 😃.");
avail=true;
PASS = localStorage.getItem(user);
if (pass!=PASS) {
alert("Please, check your password and write correctly.");
} else if(pass==PASS) {
avail='correct';
}
}
}
if(avail!=true) {
localStorage.setItem(max1, user)
localStorage.setItem(user, pass)
document.getElementById("form").action = 'main.html';
} else if(avail=='correct') {
document.getElementById("form").action = 'main.html';
}
}
}
if(avail == false){
localStorage.setItem(max1, user)
localStorage.setItem(user, pass)
document.getElementById("form").action = 'main.html';}
or
else if(pass==PASS) {
confirmed='correct';
}
There are 2 possible solutions:
check for if(avail == false)
use another variable when the password has been confirmed.
By redeclaring avail = "correct", you are changing the typeof(avail) from boolean to string. Avail will never be true because it's no longer a boolean.

I've been trying to use for loop via user input but for some reason it neither shows the error nor shows the output

I've been trying to use for loop via user input but for some reason it neither shows the error nor shows the output. here is my code below:-
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>js recap</title>
</head>
<body>
<form class="addform">
<input type="number" name="text" id="text">
</form>
<!-- START JAVASCRIPT -->
<script>
const addform = document.querySelector('.addform');
addform.addEventListener('submit', e => {
const todos = addform.text.value.trim();
e.preventDefault();
if (todos === typeof Number) {
for (let i = 0; i <= todos; i++) {
console.log(i);
}
}
});
</script>
<!-- END JAVASCRIPT-->
</body>
</html>
some notes:
e.target.value.trim() returns a string
use typeof todos === "number" or you can use !isNaN(todos) to check if a variable is a type of number ( isNaN means is not a number add the negation to it !isNaN to check if its a number )
parseInt() to convert the string retrieved from e.target.value.trim() to a number
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>js recap</title>
</head>
<body>
<form class="addform">
<input type="number" name="text" id="text">
</form>
<!-- START JAVASCRIPT -->
<script>
const addform = document.querySelector('.addform');
addform.addEventListener('submit', e => {
e.preventDefault();
const todos = parseInt(addform.text.value.trim())
if (typeof todos === "number") {
for (let i = 0; i <= todos; i++) {
console.log(i);
}
}
});
</script>
<!-- END JAVASCRIPT-->
</body>
</html>
Add a button to submit your form (click event in this example). You can use parseInt to convert string to a number data type.
var addform = document.querySelector('#text');
var boton = document.querySelector("#boton");
boton.addEventListener('click', e => {
var todos = parseInt(addform.value.trim());
e.preventDefault();
if (typeof todos === 'number') {
for (let i = 0; i <= todos; i++) {
console.log(i);
}
}
});
<input type="number" name="text" id="text">
<button id="boton"> Go </button>
Any value that a user enters via the DOM comes through as text. You need to convert it into a number and then run the loop.
You can do:
if( !isNaN( Number(todos) ))
The if statement that you have is never true. So the code never executes.
You can check it by adding a console log just for the check.
console.log('%c Check the input value.', 'background:grey; padding:10px; color:#fff', typeof todos, todos);

Captcha making, I think it is a logical error

I am having a problem in my code, I made a very simple newbie type captcha using Javascript the following is the my code.
<!DOCTYPE html>
<html>
<head>
<style>
</style>
</head>
<body>
<h1>Testing captcha</h1>
<hr>
<img id="firstImage" img src="pictureOne.jpg">
<input type="text" id="firstInput"></input>
<button type="button" onclick="checker()">Confirm</button>
<hr>
<p id="cone">Please type what you see in this picture, This is a captcha to prevent over-spamming</p>
</body>
<script>
function checker() {
var checkPic = document.getElementById('firstImage').src = 'pictureOne.jpg'
var takePic = document.getElementById('firstInput').value;
checkPic.toString()
if (checkPic === "pictureOne" && takePic === 'c' ) {
document.getElementById('firstImage').src = 'pictureTwo.jpg';
alert("Please confirm the second captcha");
} else if (checkPic === 'pictureTwo.jpg' && takePic === 'u') {
alert("Ready to download.")
}
}
</script>
</html>
How the captcha will work? Well i tried to make it simple, just like on completing the first captcha the second image will appear and then after finishing that captcha a certain task will be shown. The issue is that the code is not working. I don't know if my condition statements have problem or what so ever please help me. I am stuck in this like for 7 hours.
you have several problems in you code. I first try to fix this problems.
remove unused attribute img from <img id="firstImage" img src="pictureOne.jpg">
remove = 'pictureOne.jpg' from var checkPic = document.getElementById('firstImage').src = 'pictureOne.jpg' to get the real content of element #firstImage instead of setting it every time to pictureOne.jpg
remove line checkPic.toString(). Its not needed (and missing a ; at the end)
use == instead of === because === will test if both sides are the same thing and not only equal. Example: define i=5 and x=5 --> i==x is true but i===x is false and i===i is true
use .endsWith(" to compare your image locations because they will start with http://xyz.abc/ and you only have to check the end
<!DOCTYPE html>
<html>
<head>
<style>
</style>
</head>
<body>
<h1>Testing captcha</h1>
<hr>
<img id="firstImage" src="pictureOne.jpg">
<input type="text" id="firstInput"></input>
<button type="button" onclick="checker()">Confirm</button>
<hr>
<p id="cone">Please type what you see in this picture, This is a captcha to prevent over-spamming</p>
</body>
<script>
function checker() {
var checkPic = document.getElementById('firstImage').src;
var takePic = document.getElementById('firstInput').value;
if (checkPic.endsWith("pictureOne.jpg") && takePic == 'c' ) {
document.getElementById('firstImage').src = 'pictureTwo.jpg';
alert("Please confirm the second captcha");
} else if (checkPic.endsWith('pictureTwo.jpg') && takePic == 'u') {
alert("Ready to download.")
}
}
</script>
</html>
Now we can talk about the CAPTCHA or is your question already solved?
Try this, you are using the full url of the image, which is not always the same as "pictureOne.jpg", you need get the substring of the url from the end.
<!DOCTYPE html>
<html>
<head>
<style>
</style>
</head>
<body>
<h1>Testing captcha</h1>
<hr>
<img id="firstImage" src="pictureOne.jpg">
<input type="text" id="firstInput"/>
<button type="button" onclick="checker()">Confirm</button>
<hr>
<p id="cone">Please type what you see in this picture, This is a captcha to prevent over-spamming</p>
</body>
<script>
function checker() {
alert(123);
var checkPic = document.getElementById('firstImage').src;
var takePic = document.getElementById('firstInput').value;
checkPic = checkPic.substring(checkPic.lastIndexOf('/')+1);
if (checkPic === "pictureOne.jpg" && takePic === 'c') {
document.getElementById('firstImage').src = 'pictureTwo.jpg';
alert("Please confirm the second captcha");
} else if (checkPic === 'pictureTwo.jpg' && takePic === 'u') {
alert("Ready to download.")
}
}
</script>
</html>

JavaScript Quiz Not Working

I am trying to make a little quiz to study.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Quiz</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
</head>
<body>
<div id="question"></div>
<form>
<input type="text" id="answer">
<button onClick="check()">Check</button>
</form>
<script>
var spanish = new Array("Hola", "Sí", "No");
var english = new Array("Hello", "Yes", "No");
var x = Math.floor(Math.random()*3);
document.getElementById("question").innerHTML = english[x];
var attempt = document.getElementById("answer");
var correct = spanish[x];
function check(){
if(attempt == correct){
alert("Correct");
}else{
alert("Fail");
};
};
</script>
</body>
</html>
It is returning Fail no matter if I am right or not. Do you know how to fix this? I looked around but could not figure out what is wrong. Thanks.
You need to check for attempt upon clicking the button. You're currently checking it on page load (so it's always an empty string, which is causing correct == attempt to be false). Also, you need to grab the value, not the element.
So, change your function to:
function check() {
var attempt = document.getElementById("answer").value;
if (attempt == correct) {
alert("Correct");
} else {
alert("Fail");
};
};
See here: http://jsfiddle.net/ykZHa/

Cant remove childnode without making childNode (message) not showing at all

I've have tried alot of different ways with removing the child and nothing has worked so faar, well it has to some degree, either i have no messages or i keep getting message that just add to the span without deleting the other
Tried reading up on how to remove the child, and have tried every different ways i've found to remove it, my code might be wrong on creating the child and append it etc. since it's the first time i use this way. Been trying with a while loop to remove, and the one that is already outcommented in the code, and with firstChild. and with different names instead of msg.
My code looks like this in my script:
function validateName(input, id)
{
var res = true;
var msg = document.getElementById(id);
var error = document.createElement("span");
var errorMsg = "";
if (input == "" || input < 2) {
res = false;
// removeChildren(msg);
errorMsg = document.createTextNode("Input is to short!");
error.appendChild(errorMsg);
id.appendChild(error);
}
if (input >= 2 && input.match(/\d/)) {
res = false;
// removeChildren(msg);
errorMsg = document.createTextNode("Name contains a number!");
error.appendChild(errorMsg);
id.appendChild(error);
}
if (input >= 2 && !input.match(/\d/)) {
res = true;
// removeChildren(msg);
}
return res;
}
My small test page:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<script src="Validator.js"></script>
<script>
function v1(e,id) {
if(validateName(document.form1.namefield.value, id) == false) {
document.getElementById("be").src="NotOkSmall.jpg";
}
if(validateName(document.form1.namefield.value) == true) {
document.getElementById("be").src="OkSmall.jpg";
}
}
</script>
</head>
<body>
<h1>Validation testing, HO!</h1>
<form name="form1" action="submit">
<div id="div1">
<input type="text" name ="namefield" id="f1" onkeydown="v1(be, div1)" >
<image id="be" src="NotOkSmall.jpg" alt="OkSmall.jpg" />
</div>
<input type="button" value="GO" onClick="v1(be)">
</form>
</body>
</html>
If anyone have any ideas to make it work I for one, would be a very happy guy :), as i have said before i am not even sure the creation of child is the correct way in this case. but as it works when i have removed removeChildren, it does write the correct messages, just dont delete any of them. So something must work..
Thanks.
You had some errors in your code like id.appendChild(error); where you had to use msg.appendChild(error);. Anyway I don't see a need to append/remove child nodes in this case. Just use hidden error placeholder and show it when you want to display an error message.
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JSP Page</title>
<script src="Validator.js"></script>
<script>
function v1(imgId) {
var img = document.getElementById(imgId),
val = document.form1.namefield.value;
img.src = img.alt = validateName(val)
? "OkSmall.jpg"
: "NotOkSmall.jpg";
}
</script>
</head>
<body>
<h1>Validation testing, HO!</h1>
<form name="form1" action="submit">
<div id="div1">
<input type="text" name ="namefield" id="f1" onkeyup="v1('be');" >
<image id="be" src="NotOkSmall.jpg" alt="NotOkSmall.jpg" />
<span id="error-message" class="invis"></span>
</div>
<input type="button" value="GO" onClick="v1('be');">
</form>
</body>
</html>​​​​​​​​​
CSS:
​.invis {
display: none;
}​
JavaScript:
function validateName(input) {
var res = true,
errorMsg,
errorContainer = document.getElementById('error-message');
if(input.length < 2) {
res = false;
errorMsg = "Input is to short!";
}
if(input.length >= 2 && /\d/.test(input)) {
res = false;
errorMsg = "Name contains a number!";
}
if(res) {
errorContainer.style.display = 'none';
} else {
errorContainer.innerHTML = errorMsg;
errorContainer.style.display = 'inline';
}
return res;
}​
DEMO

Categories

Resources