password validation - 5 tries - javascript

ok so i did a javaScript page when you click the correct password and you will be transferred to another site. now i need to make it that you can only try 5 times and every time you fail an alert will show you how many time you have. after you will try 5 times and fail you will get a massage every time you try again that says "you cant try again" or something like that. (i do aware that this is an insecure way to apply passwords) thank you very much. (also i need it with plain javaScript) the code -
<script type="text/javascript">
var password = ["1234", "abcd", "0000", "1111", "4321"];
document.getElementById('press').onclick = function () {
var p = document.getElementById("putPass").value;
if (password.indexOf(p) > -1) {
window.open("http://www.walla.com");
} else {
alert("try again!");
}
}
</script>

var badpass_counter = 0;
document.getElementById('press').onclick = function () {
if (badpass_counter >= 5) {
alert("sorry, too many failures!");
return;
}
var p = document.getElementById("putPass").value;
if (password.indexOf(p) > -1) {
window.open("http://www.walla.com");
} else {
alert("try again!");
badpass_counter++;
}
}

Set a cookie value for counter when a password is sent to server and increment that counter if password fails to match.

Related

How to select two input fields at once and check if they are filled?

So I am making a game and I need to check if these two HTML <input> fields have some data before I do an alert(); saying that they won. Unfortunately, I don't know how to implement this and I have been stuck at it for hours, please do help, attaching a screenshot for assistance.
In the image, I want to constantly monitor the 2 empty <input> fields and once there is data IN BOTH, then I want to throw up an alert();
Here's what I tried:
var firstLetterField = document.querySelectorAll("input")[0].value.length;
var secondLetterField = document.querySelectorAll("input")[1].value.length;
if (!firstLetterField && !secondLetterField) {
console.log("Please ignore this message: NOT_FILLED...");
} else {
alert("That's right! The word was " + spellingOfWord.join("").toUpperCase() + "! Thanks for playing!");
window.location.href = "/";
}
How about just adding a common class to your user input and use querySelectorAll to perform your check ?
eg
<html>
<body id="game">
<input data-expected="m" class="user-input" />
<input data-expected="a" class="user-input" />
<div id="keyboard">
<button>d</button>
<button>c</button>
<button>b</button>
<button>a</button>
<button>d</button>
<button>m</button>
<button>e</button>
</div>
</body>
<script>
const inputs = document.querySelectorAll(".user-input");
const keyboard = document
.querySelector("#keyboard")
.querySelectorAll("button");
let inputPosition = 0;
function nextInput() {
inputPosition += 1;
if (inputPosition === inputs.length) {
alert("you won");
}
}
function handleClick(event) {
const input = inputs.item(inputPosition);
const submittedValue = event.target.innerHTML;
if (input.dataset.expected === submittedValue) {
input.value = submittedValue;
setTimeout(nextInput);
}
}
keyboard.forEach((button) => button.addEventListener("click", handleClick));
</script>
</html>
You could register an event-listener and check if your condition is met:
var firstLetterField = document.querySelectorAll("input")[0];
var secondLetterField = document.querySelectorAll("input")[1];
// Function to call when both inputs contain values
function bothReady() {
console.log("bothReady", firstLetterField.value, secondLetterField.value);
}
document.addEventListener("keyup", function (e) {
// Wait for both fields to have values
if (firstLetterField.value.length > 0 && secondLetterField.value.length > 0) {
bothReady();
}
});
Your code just works fine. There were just some mistakes that I noticed.
You tried to use the length to detect if it is empty. You could instead compare it with an empty string.
You reversed the boolean value using else. It looks that does the opposite of what you want.
In the code you showed you didn't actually defined spellingOfWord. So I did it for you.
The location "/" is not compatible in every server. So I would recomment replacing it by "index.html".
Here is the code that I just created
function input_inputEvent() {
var firstLetterField = document.querySelectorAll("input")[0].value;
var secondLetterField = document.querySelectorAll("input")[1].value;
var thirdLetterField = document.querySelectorAll("input")[2].value;
if (firstLetterField.length != "" && secondLetterField != "") {
alert(
"That's right! The word was " +
[firstLetterField,secondLetterField,thirdLetterField].join("").toUpperCase() +
"! Thanks for playing!"
);
window.location.href = "index.html";
}
}

Javascript - simple counting

This is my first post and second day with Javascript ;). I try to create a simple form, which:
Allows user put any letter / letters in an input field.
Than I want to send it to my script and:
a) check if anything was given in a form
b) if the user put any sign i want to put it in an array and count up the number of tries
c) if the number of tries reach 10 I want to to stop the script
My script doesn't remeber the number of tries. Moreover, it saves the data in an array but after the script is done it erases everything (I put some console.log() in the script, to see if it does anything). It looks like my variable count doesn't remember the number of tries :(.
How can I fix it ? - but in a simple way of coding :) (I don't want to do a lot of changes in my code)
<script type= "text/javascript">
var given_letters = []; // create an empty array
function givenLetter() {
var count = 0;
var max_count = 10;
var letter = document.getElementById('letter').value;
while (count < max_count) {
if (letter === "") {
alert("No letter given");
return false;
} else {
count++;
given_letters.unshift(letter);
console.log(letter); // returns letter
console.log(given_letters); // returns array with 1 element
console.log(count); // returns "1"
alert("OK");
return true;
}
}
while (count === max_count) {
alert("Sorry. You exceeded the limit of tries.");
return false;
}
}
</script>
// in BODY section
<div>
<form><p>Put your letter here: <input type="text" id="letter" size="5" required><button onclick="givenLetter();">Send</button></p></form>
</div>
You can use given_letters.length instead of count, less code and its the same value, you need to use e.preventDefault(); so the form doesnt submit the form yet, here its a working example, for e.preventDefault(); to work you need to send the event in the button, like this:
<div>
<form>
<p>Put your letter here: <input type="text" id="letter" size="5" required>
<button onclick="givenLetter(event);">Send</button></p>
</form>
</div>
the JS updated:
var given_letters = []; // create an empty array
function givenLetter(e) {
e.preventDefault();
var max_count = 10;
var letter = document.getElementById('letter').value;
while (given_letters.length <= max_count) {
if (letter === "") {
alert("No letter given");
return false;
}
else {
given_letters.unshift(letter);
console.log(letter); // returns letter
console.log(given_letters); // returns array with 1 element
console.log(given_letters.length);//here is your count already
alert("OK");
return true;
}
}
while (given_letters.length === max_count) {
alert("Sorry. You exceeded the limit of tries.");
return false;
}
}
The default behaviour of a button in a form is to submit the form... and reload the page (quite stupid, IMO). This is why your script doesn't seem to remember anything. But there's a way to prevent that.
Also, write var count = 0; outside the function, otherwise it's being set to 0 every time the function is called.
var count = 0;
function givenLetter(event) {
event.preventDefault();
// ....
Try this.
Since the button i within the form tag the default behavior of button is submit. so the form will be submitted and reload the page. So to prevent that behavior we use event.preventDefault(); and make count as a global variable.
var given_letters = []; // create an empty array
var count = 0;
function givenLetter() {
event.preventDefault(); //to prevent reloading the page.
var max_count = 10;
var letter = document.getElementById('letter').value;
while (count < max_count) {
if (letter === "") {
alert("No letter given");
return false;
}
else {
count++;
given_letters.unshift(letter);
console.log(letter); // returns letter
console.log(given_letters); // returns array with 1 element
console.log(count); // returns "1"
alert("OK");
return true;
}
}
while (count === max_count) {
alert("Sorry. You exceeded the limit of tries.");
return false;
}
}
<div>
<form>
<p>Put your letter here: <input type="text" id="letter" size="5" required>
<button onclick="givenLetter();">Send</button></p></form>
</div>

If and Else Statements Always Output If

I was messing around with a previously existing snippet and ran into an issue.
Whenever I try to enter an input that doesn't apply the to If statement it always gives me the If output. Also I was looking to, instead of saying approved, have you sent to a URL, like Google for example, and I'm not sure about a solution for either of the two.
function myFunction() {
var a = document.getElementById("text_a").value;
if (a == "02035", "02048", "02067") {
document.getElementById("answer").innerHTML = "Approved";
} else {
document.getElementById("answer").innerHTML = "Our service currently isn't available in your area! Try again soon!";
}
}
<p>Enter Zip Code </p>
<input id="text_a" type="text" />
<p id="answer"></p>
<button onclick="myFunction()">Check</button>
May be you need to change the condition in if statement:
if (a == "02035" || a == "02048" || a == "02067"){
document.getElementById("answer").innerHTML="Approved";
}
else{
document.getElementById("answer").innerHTML="Our service currently isn't available in your area! Try again soon!";
}
if (a=="02035","02048","02067")
You can't do like this.
There are many ways to check it. You could do like this
function myFunction() {
var a = document.getElementById("text_a").value;
var list = ["02035", "02048", "02067"];
console.log(a)
if ((list.indexOf(a) > -1)) {
document.getElementById("answer").innerHTML = "Approved";
} else {
document.getElementById("answer").innerHTML =
"Our service currently isn't available in your area! Try again soon!";
}
}
I made a sample: https://codepen.io/anon/pen/bWBvMj?editors=1011

Having difficulty getting Javascript form to validate

Been looking for an answer for hours now and I still haven't come up with a solution. I've tried looking for similar question, but none have helped, really.
So basically, what doesn't work is that the form submits without any error messages even if there are mistakes on the form. Basically, I could leave the name field empty and the form will still submit once I press the button. Hope this made sense. Any help is appreciated
Code:
function validateFinale()
{
var emailOne = document.getElementById("em1").value;
var emailTwo = document.getElementById("em2").value;
var name = document.getElementById("name1").value;
if (compare())
{
if (name, 'Please enter name'))
{
if (validEmail(getElementById('em1'), 'Email invalid'))
{
}
}
}
return false;
}
function validName(elem, helpmsg) {
if (elem.value.length == 0) {
alert(helpmsg);
return false;
} else {
return true;
}
}
function validEmail(elem, msg) {
var wrongem = /^[\w\-\.\+]+\#[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]+$/;
if (elem.value.match(wrongem)) {
return true;
} else {
alert(msg);
return false;
}
}
function compare() {
if (emailOne != emailTwo) {
alert("Emails not the same");
submitOk = "false";
Document.getElementById("em1").value = " ";
Document.getElementById("em2").value = " ";
Document.getElementById("em1").focus();
} else {
alert("form complete, thank you");
}
}
http://jsfiddle.net/aj240/qgmt5yr8/
you made syntax mistake, first you declare emailOne as local variable, than try reach it in global scope. You should declare variables emailOne and emailTwo in global scope.
var emailOne;
var emailTwo;
function validateFinale()
{
emailOne = document.getElementById("em1").value;
emailTwo = document.getElementById("em2").value;
var name = document.getElementById("name1").value;
One gold tip, try press F12 in your browser and all errors messages would appear in console.
Try setting required ="true" in the input elems:
<input type="text" required ="true"...
Also, if you set type="email" in the e-mail field it will ask for an e-mail address (not at all, though, it just will accept anything with an "#")
And the code validName(getElementById('name1'), ...) should be validName(getElementById('name1').value, ...), or else you'll get all the HTML element

Password Page Alert Box

I need to put a password protect in one my page. But I want it in a way that when the user click on a menu in my navigation, example is "Gallery", I want an alert box, saying "Enter password to view content" I have used the code below, but it still need to have a button and I don't want that.
P.S. And I prefer to use javascript and html only.
function passWord() {
var testV = 1;
var pass1 = prompt('Enter password to view content',' ');
while (testV < 3) {
if (!pass1)
history.go(-1);
if (pass1.toLowerCase() == "123456789") {
alert('You Got it Right!');
window.open('/gallery');
break;
}
testV += 1;
var pass1 = prompt('Access Denied - Password Incorrect, Please Try Again.','Password');
}
if (pass1.toLowerCase()!="password" & testV == 3){
history.go(-1);
return " ";
}
}
Passwords in javascript are trivial to circumvent, and in this case, they could find the password by looking at the source.
Having said that, you could trigger your code by using onclick - <div class="mymenu" onclick="password();">
EDIT:
Also, (!pass1) is invalid syntax, did you mean (pass==null)?

Categories

Resources