set of passwords in arrays, the user only has 3 chances - javascript

I need to make an array of passwords looping for the user to be redirected to another site. After 3 mistakes the user cannot try again. This is what I have so far, but it doesn't work.
<form>
<label>Please enter Password</label>
<input type="text" id="Pass" />
<input type="button" value="go" onClick="check()" />
</form>
<script type="text/javascript">
function check()
{
var password = ["123","456","789"]
for(a=0;a=password.length;a++)
{
if (user="password")
{
document.location.href="http://yahoo.com";
}
else
{
alert("wrong password");
}
}
}
</script>

As you are calling a function check from the onclick event, you need a function by that name in your code.
When calling the check function you can pass along the value from the text box, so that the function can use it to check against the items in the array.
In your code the condition for the loop is wrong. Using a=password.length means that the loop won't run at all. The loop runs as long as the condition is true, it's not used to mark the end of the loop.
Use the == operator to check if two values are equal (the = operator is for assignment). Use password[a] to get the item from the array which has the index from the variable a.
In the loop you should only check for when the strings are equal. If you have an else case there, it will tell you that the password is wrong for every password that didn't match. Use return to exit from the function when you have set the location.
After the loop you know that none of the password matches, so then you know that the password was wrong.
<body>
<form>
<label>Please enter Password</label>
<input type="text" name="Pass" />
<input type="button" value="go" onclick="check(this.form.Pass.value)"/>
</form>
<script type="text/javascript">
var password = ["123","456","789"];
function check(pass) {
for(a = 0; a < password.length; a++) {
if (pass == password[a]) {
document.location.href="http://yahoo.com";
return;
}
}
alert("wrong password");
}
</script>
</body>

Related

I want to restrict users from entering number ending with 5

Here is text field.I want users to only enter value like 210,220,230,... and restrict from entering something like 215,225,...
I am looking for suggetions.I don't have much knowledge of javascript.
If you just want to prevent strings that end in '5':
document.getElementById("input").onblur = checkEND;
function checkEND() {
let firstValue = event.currentTarget.value;
if(firstValue.endsWith('5')){
warnUser()
}
}
This won't validate that the string is a valid number though.
function testInput() {
var key = window.event.keyCode;
var x = document.getElementById('textarea').value
var y = document.getElementById('textarea2').value
var z = parseInt(x, 10);
if (z+10 == y) {
document.getElementById('result').innerHTML = "valid";
} else {
document.getElementById('result').innerHTML = "invalid";
}
}
<textarea maxlength="3" id="textarea">5</textarea>
<textarea maxlength="3" id="textarea2">15</textarea>
<button onclick="testInput()">Test Input</button>
<div id="result"></div>
The first input is your first number, the second is your second number.
See Comments If Your Wondering Why This Doesn't Answer His OG Question
You can experiment with the setCustomValidity() of input elements (https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement) from an onblur, onchange or oninput handler. If you are not satisfied with the value, set an error message, and an empty string otherwise. As long as the error message is set to non-empty, it is displayed and the form refuses to submit:
function check5() {
cgiftcardq.setCustomValidity(cgiftcardq.value.endsWith('5')?"Nope, it can not end with 5":"");
}
<form>
<input name="cgiftcardq" class="text_field" id="cgiftcardq" size="3" autocomplete="off" type="text" onblur="check5()">
<input type="submit" value="Send">
</form>
(StackOverflow snippets interfere with form submission - probably as part of security -, so successful submission just makes the form disappear)
As setCustomValidity() does not work everywhere (according to the compatibility table, it will not work on non-Andorid mobiles), classic "budget" solution may be mentioned too: you can simply disable the send button as long as you are not satisfied with the input:
function check5() {
if(cgiftcardq.value.endsWith('5')){
send.disabled=true;
message.innerHTML="Nope, it can not end with 5";
} else {
send.disabled=false;
message.innerHTML="OK";
}
}
<form>
<input name="cgiftcardq" class="text_field" id="cgiftcardq" size="3" autocomplete="off" type="text" oninput="check5()">
<input id="send" type="submit" value="Send" disabled>
</form>
<div id="message"></div>

Prevent multiple alert on "oninvalid" html

I was thinking, can i stop the alerts after the first?
I'll explain it better, every time I confirm the form, start an aler for every input that has oninvalid.
so if i have 10 inputs, i'll have 10 alarms. Is it possible to interrupt them after the first one?
<form>
<input type="text" oninvalid="alert('test1')" required />
<input type="text" oninvalid="alert('test2')" required />
<button>Send</button>
</form>
Fiddle: https://jsfiddle.net/9d1L5pxd/1/
You can consider doing something like I demonstrate below. Basically just add an event handler to the send button, which will call a validation function on your form each time it's clicked.
The validation function checks all the text type field values. If a text field with an invalid value is encountered, the function will return false (stop immediately).
If the function doesn't find any problems with the user input then it will return true. You can use the return value to determine if the form should be submitted or whatever if you need to.
var btnSend = document.getElementById('btnSend');
btnSend.addEventListener('click', function() {
var isValid = validateForm();
if (isValid)
console.log('Form is ready to submit.');
});
function validateForm() {
var formToValidate = document.getElementById('dataForm');
var elements = formToValidate.elements;
var i;
for (i = 0; i < elements.length; i++) {
if (elements[i].type == 'text') {
//replace this with your actual validation
var invalid = elements[i].value.length == 0;
if (invalid) {
alert(elements[i].id + ' is invalid.');
return false;
}
}
}
return true;
}
<form id="dataForm">
<input id="field1" type="text" required />
<input id="field2" type="text" required />
<input id="btnSend" type="button" value="Send">
</form>

Insert missing letter javascript game

I'm making a language learning game with javascript. I want the user to be able to write the missing letter and the results to be validated through javascript if they are right or wrong.
<form>
De<input id="letterone" type="text" name="latter" pattern="[A-Za-z]{1}">
ign<input id="lettertwo" type="text" name="latter" pattern="[A-Za-z]{1}">r
<input type="submit">
</form>
My javascript code.
if ((getElementById('letterone')==='s') && (getElementById('lettertwo')==='e')) {
alert('Correct');
}else{
alert('Wrong');
}
There are number of errors on your code :
No 'document' before getElementById
No 'value' after the object
No click handler
Incorrect id while accessing the object
Using input type=submit causes an unwanted page refresh as Useless Code comments below.
document.getElementById('submit').addEventListener('click', function() {
if ((document.getElementById('latterone').value==='s') && (document.getElementById('lattertwo').value==='e')) {
alert('Correct');
}else{
alert('Wrong');
}
});
<form>
De<input type="text" id="latterone" pattern="[A-Za-z]{1}">
ign<input type="text" id="lattertwo" pattern="[A-Za-z]{1}">r
<input type="button" id="submit" value="Submit">
</form>
var lOne = document.getElementById('letterone').value; // get the value of the first input
var lTwo = document.getElementById('lettertwo').value; // get the value of the second
if (lOne === 's') && lTwo === 'e') {
alert('Correct');
}else{
alert('Wrong');
}

Why won't my alert work in one of my functions?

I want the nameVerification() function to throw the alert() message when the user hits submit. For example, if the user enters something like 45 in the name field, I want that alert in nameVerification() function to be called. Right now, when the user does type in a number in the name field, the alert() in the formSubmission() function is being called.
Side note:
formSubmissionfunction works perfectly. In other words, if the user enters a number < 13 in the age field, the functions alert() gets called normally with no problems. If the user enters a number > 13, it works, also, without a problem. Just thought I'd let you guys know that too.
signUp.html
<!DOCTYPE html>
<html>
<head>
<title>Signup Form</title>
<script type="text/javascript" src="signUp.js"></script>
</head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="signUp.css">
<body>
<form class="col-md-4 col-md-offset-4" name="formHandler" id="handle">
<div class="moveUsername">
<label for="usr">Name:</label>
<input type="field" class="form-control" id="nameVerify" placeholder="Username" required="required">
</div>
<div class="ageMovement">
<label for="usr" >Age (Must be 13 years or older to play):</label>
<input type="field" class="form-control" id="ageVerify" name="ageChecker" placeholder="Age" required="required">
</div>
<button type="submit" class="btn btn-default" onclick="formSubmission()" onclick="nameVerification()">Submit</button>
</form>
</body>
</html>
signUp.js
function nameVerification() {
var name = document.getElementById("nameVerify").value;
if(typeof name !== 'string') {
alert("That's not a name!");
}
}
function formSubmission() {
var age = document.getElementById("ageVerify").value;
if(age < 13) {
alert("You're too young, you can't play the game");
}
}
age is also a string in this function:
function formSubmission() {
var age = document.getElementById("ageVerify").value;
if(age < 13) {
alert("You're too young, you can't play the game");
}
}
If you want to do a numeric compare, you need to parse first:
function formSubmission() {
var age = document.getElementById("ageVerify").value;
if (age) {
var ageInteger = parseInt(age, 10);
if (ageInteger < 13) {
alert("You're too young, you can't play the game");
}
}
}
You have two onclick attributes on the button
<button type="submit" class="btn btn-default" onclick="formSubmission()" onclick="nameVerification()">Submit</button>
You can only have one
Your typeof test is failing because the value returned from a text input is always of type string. You can test to see if a provided text value is numeric with the following function:
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
The real answer, however, is that you'll need to improve your input validation tests to determine what you want, rather than test for all the things you don't want. For example, testing for a numeric value as above would not work if someone entered "t#^!" in the field, which is likely not a value you would want in a name field. This is where regular expressions, and the built-in validations from HTML5 fields can help.
You can change your nameVerification function as follows:
function nameVerification() {
var name = document.getElementById("nameVerify").value;
if (name) {
var num = parseInt(name) || -1;
if (num >= 0 && num < 13) {
alert("That's not a name!");
}
}
}
and change your onclick values in the html to be:
onclick="formSubmission();nameVerification()"
it's because the javascript is not loaded yet.
Move:
<script type="text/javascript" src="signUp.js"></script>
To just above the </body> tag.
You should use parseInt:
var age = parseInt(document.getElementById("ageVerify").value);

Showing all error messages at the same time in form validation

Why are my conditional statements not working properly? I want to display bothe error messages at the same time.
function validate() {
if (firstName.value == "") {
document.getElementById('error').innerHTML = "*Field is empty";
return false;
} else if (lastName.value == "") {
document.getElementById('errorTwo').innerHTML = "*Field is empty";
return false;
} else {
return true;
}
}
<form name="form" action="action.php" method="post" onsubmit="return validate()">
<div class="wrapper">
<span>Name</span>
<br>
<input type="text" name="firstName" id="firstName" placeholder="First Name" onfocus="this.placeholder=''" onblur="this.placeholder='First Name'" />
<label id="error"></label>
<br>
<input type="text" name="middleName" id="middleName" placeholder="Middle Name (optional)" onfocus="this.placeholder=''" onblur="this.placeholder='Middle Name (optional)'" />
<input type="text" name="lastName" id="lastName" placeholder="Last Name" onfocus="this.placeholder=''" onblur="this.placeholder='Last Name'" />
<label id="errorTwo"></label>
<br>
<br>
</div>
Your conditional statements are working correctly, your understanding of them is a little off though.
An if / else if statement will stop running when a condition is matched, so if firstName.value is empty, then that if statement will be matched and the code will exit there and not evaluate the rest of the conditions.
You want to use independent conditional statements for each test, and instead of returning either true or false, set a variable to true or false and return that after the conditional checks.
So...
function validate()
{
var valid = true;
if(firstName.value=="")
{
document.getElementById('error').innerHTML="*Field is empty";
valid = false;
}
if(lastName.value=="")
{
document.getElementById('errorTwo').innerHTML="*Field is empty";
valid = false;
}
return valid;
}
Just a note on the code itself, the above comments are mainly correct, if you post your entire code, you'll probably get more helpful responses. Also, you can eliminate the =="" part of the checks and just test the value of the variable as an empty string evaluates to false.
Don't chain the validations together with if-else otherwise if the first name validation fails, then you will never check the last name validation.
Help yourself by quickly creating a JsFiddle :-)
Here it is:
http://jsfiddle.net/23tnpve4/1/
You will easily see some issues by trying:
As others mentioned, missing brackets etc
As others mentioned, if the first test fails the other fields are not checked so errors can by corrected only step by step.
There is no code that refreshes your error DIVs. In a new form check, the error fields have to be cleared first. Checking forms are cycles with several possible start statuses.
Try to collect the status of fields in an array and work them later, something like this:
window.validate = function()
{
var firstName = document.getElementById('firstName');
var lastName = document.getElementById('lastName');
// Clear
firstName.val('');
lastName.val('');
// Check
var errorNames = [];
if(firstName.value=="")
{
errorNames.push('firstName');
}
if(lastName.value=="")
{
errorNames.push('lastName');
}
// Inform
for (var i=0; i<errorNames.length; i++) {
document.getElementById(errorNames[i]).innerHTML="*Field is empty";
}
// Return value
return errorNames.length == 0;
}
The concept of this code will work more intuitively. I haven't checked it against typos, it is a draft, but I do hope it will help you.

Categories

Resources