Javascript - Compare user input value to randomly generated value - javascript

I have a function that displays a random word from an array, in a non-repeated way, and a textbox where the user is supposed to type the same generated word.
I tried using a switch statement to validate the user's answer, comparing his input to the randomly generated word, but it is not working.
My question is, is it even possible to compare such things? And if so, how?
This is my code:
// Generate random, non-repeated word
const p = document.getElementById("randomWord");
const origWords = ["alpha", "bravo", "charlie", "delta", "echo"];
let remainingWords = [];
function randomize() {
if (remainingWords.length === 0) remainingWords = origWords.slice();
const {
length
} = remainingWords;
const [quote] = remainingWords.splice(Math.floor(Math.random() * length), 1);
p.textContent = quote;
}
randomize();
// Validate answer
function submit001() {
var answers = document.getElementById("input001").value.toLowerCase();
switch (answers, remainingWords) {
case "":
text = "Please write something.";
break;
case answers == remainingWords:
text = "Correct.";
randomize();
break;
default:
text = "Wrong.";
}
document.getElementById("comment").innerHTML = text
}
<input type="text" id="input001" autofocus maxlength="7" spellcheck="false" onKeyDown="if(event.keyCode==13) submit001();">
<p id="randomWord"></p>
<p id="comment"></p>

An if statement is probably a more appropriate solution to the problem. Try this:
// Generate random, non-repeated word
const p = document.getElementById("randomWord");
const origWords = ["alpha", "bravo", "charlie", "delta", "echo"];
let remainingWords = [];
function randomize() {
if (remainingWords.length === 0) remainingWords = origWords.slice();
const length = remainingWords;
const [quote] = remainingWords.splice(Math.floor(Math.random() * length), 1);
p.textContent = quote;
}
randomize();
// Validate answer
function submit001() {
var answers = document.getElementById("input001").value.toLowerCase();
if (answers == "") {
text = "Please write something.";
} else if (answers == p.textContent) {
text = "Correct.";
randomize();
} else {
text = "Wrong.";
}
document.getElementById("comment").innerHTML = text
}
<input type="text" id="input001" autofocus maxlength="7" spellcheck="false" onKeyDown="if(event.keyCode==13) submit001();">
<p id="randomWord"></p>
<p id="comment"></p>

Related

How do i remove a calculator from a bot? (its connected to the enter button)

I need to remove the calculator, without removing the function of allowing it to print, I have tried switching things around, and removing things, but still when I type in a number, such as 67, it comes out as 67=67, or more complicated math equations, it dosent except things like PI, this is because it thinks it's some symbol, not a character. The only things that do work are: / = + - /, it dosent accept cubed or squared, or to the power of X
Bot code:
<html>
<body>
<div class="container" id="content">
<p id="out">
</p>
<p id="inp">
<div id="stretchbox" style = "position:fixed; left:80px;">
<input type="text" placeholder="Coin ID #"
id="txt-inp"
autocomplete="off"
autocorrect="off"
autocapitalize="off"
autofocus="autofocus"
spellcheck="false">
</input>
</div>
</p>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
$(function() {
var trigger = [
["25184"],
["27123"],
["26124"],
["17453"]
];
var reply = [
["Coin Bot - "],
["Tokyn Blast - "],
["Iron Wolf - "],
["Foxyville - "],
];
var alternative = ["I cant find that Coin ID # right now, make sure that the Coin ID # exist!"];
let textInput = $('#txt-inp');
let messageOutput = $('#out');
let processingStatus = $('<span>Bot: Processing...<br></span>');
let name = 'You';
function println(text) {
let newSpan = document.createElement("SPAN");
let newLine = document.createElement("BR");
let textNode = document.createTextNode(text);
newSpan.appendChild(textNode);
document.getElementById("out").appendChild(newSpan);
document.getElementById("out").appendChild(newLine);
gotoBottom();
}
function print(text) {
let newSpan = document.createElement("SPAN");
let textNode = document.createTextNode(text);
newSpan.appendChild(textNode);
document.getElementById("out").appendChild(newSpan);
}
function gotoBottom() {
window.scrollTo(0,document.body.scrollHeight);
}
function sendMessage() {
let data = {
'reply': textInput.val()
};
if (!data['reply']) {
return;
}
println(name + ': ' + data['reply']);
textInput.val('');
messageOutput.append(processingStatus);
textInput.attr('disabled', 'disabled');
messageOutput.children().last().remove();
textInput.removeAttr('disabled');
output(data['reply']);
}
$('#txt-inp').keypress(function(e) {
if (e.which == 13) {
sendMessage();
}
});
function output(input){
try{
var product = input + "=" + eval(input);
} catch(e){
var text = (input.toLowerCase()).replace(/[^\w\s\d]/gi, ""); //remove all chars except words, space and
text = text.replace(/!/g, "!").replace(/i feel /g, "").replace(/whats/g, "what is").replace(/please /g, "").replace(/ please/g, "");
if(compare(trigger, reply, text)){
var product = compare(trigger, reply, text);
} else {
var product = alternative[Math.floor(Math.random()*alternative.length)];
}
}
println(product);
}
function compare(arr, array, string){
var item;
for(var x=0; x<arr.length; x++){
for(var y=0; y<array.length; y++){
if(arr[x][y] == string){
items = array[x];
item = items[Math.floor(Math.random()*items.length)];
}
}
}
return item;
}
});
</script>
</body>

How to populate multiple HTML DOM elements with local storage values

I want to display contents in the last <div> element when a click event occurs but now it only shows 1st 2 elements. Is there something I am not doing right somewhere?
Here is my code so far:
JS
const iname = document.getElementById("name");
const iemail = document.getElementById("email");
const iphone = document.getElementById("phone");
const submit = document.getElementById("submit");
const storage = document.getElementById("storage");
submit.onclick = function () {
const name = iname.value;
const email = iemail.value;
const phoneno = iphone.value;
if (name && email && phoneno) {
localStorage.setItem(name, "");
localStorage.setItem(email, "");
localStorage.setItem(phoneno, "");
location.reload();
}
};
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
const value = localStorage.getItem(key);
storage.innerHTML += `Name : ${key}<br />Email : ${value}`;
}
localStorage.clear()
HTML
<p>Name</p>
<input id="name" autocomplete="off">
<p>Email</p>
<input id="email" autocomplete="off">
<p>Phone no</p>
<input id="phone" autocomplete="off">
<button id="submit">Let's go</button>
<div id="storage" class="box">
<h1>Is this correct?</h1></div>
I think you are setting the values in localstorage the wrong way.
The syntax for storing stuff in there is localstorage.setItem(keyName, keyValue).
And your code is setting the keyName argument to the value you are getting from the form and keyValue argument to an empty string; not what you need.
Make the following changes and you should be good to go (see comments):
submit.onclick = function () {
const name = iname.value;
const email = iemail.value;
const phoneno = iphone.value;
if (name && email && phoneno) {
// set local storage values
localStorage.setItem("name", name); // modified
localStorage.setItem("email", email); // modified
localStorage.setItem("phoneno", phoneno); // modified
location.reload();
}
console.log(localStorage); // new (maybe unnecessary)
};
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
const value = localStorage.getItem(key);
storage.innerHTML += `${upFirst(key)}: ${value}<br>`; // modified
}
localStorage.clear();
/**
* new: making the first letter an upper case (for labels in the output div).
* See usage in 'for loop' above.
*/
function upFirst(stringValue) {
return stringValue.slice(0, 1).toUpperCase() + stringValue.slice(1);
}

Sign In prompt with javascript/HTML

I have this sign in prompt that allows the user to enter a valid email address and then enter a password consisting of at least one number, one special character and at least 8 or more characters. Then the user would enter the password again, and the code ensures that it matches. It also implements a strength meter to tell the user how strong the password is.
I have the meter implementing strength based on the characters entered but, I cannot figure out how to implement the length of the password. Right now if the user enters a letter, number, and special character it states that it is strong. But I need it to also have at least 8 characters as well.
This is the specific function that I believe needs adjusting;
// Function for password strength meter
function PasswordMeter(password) {
if (password.length === 0) {
document.getElementById("msg").innerHTML = "";
return;
}
var matchedCase = new Array();
matchedCase.push("[$#$!%*#?&]"); // Special Charector
matchedCase.push("[0-9]"); // Numbers
matchedCase.push("[a-z]"); // Lowercase Alphabates
var ctr = 0;
for (var i = 0; i < matchedCase.length; i++) {
if (new RegExp(matchedCase[i]).test(password)) {
ctr++;
}
}
var color = "";
var strength = "";
switch (ctr) {
case 0:
case 1:
strength = "Weak: Keep going...";
color = "red";
break;
case 2:
strength = "Medium: A little better but add more..";
color = "blue";
break;
case 3:
strength = "Strong! Now that is good!";
color = "green";
break;
}
document.getElementById("msg").innerHTML = strength;
document.getElementById("msg").style.color = color;
}
And just for better perspective this is the rest of my code... I am so close to this being perfect just need a little guidance on this one piece, so thank you in advance for any advice/help!
<!DOCTYPE html>
<html>
<head>
<style>
</style>
</head>
<body>
<h3>Sign In</h3>
<div class="container">
<form action="/action_page.php">
<label for="userId">UserId:</label>
<input type="email" id="userId" name="email" pattern="[a-zA-Z0-9._%+-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,3}$" required>
<br>
<br>
<label for="psw1">Password:</label>
<input type="password" id="psw1" name="psw1" pattern="(?=.*[a-z])(?=.*[0-9])(?=.*[!##$%^&*_=+-]).{8,}" title="Must contain at least one number, one special character and at least 8 or more characters" onkeyup="PasswordMeter(this.value);"/><span id="msg"></span>
<br>
<br>
<label for="psw2">Password:</label>
<input type="password" id="psw2" name="psw2" pattern="(?=.*[a-z])(?=.*[0-9])(?=.*[!##$%^&*_=+-]).{8,}" title="Must contain at least one number, one special character and at least 8 or more characters" required>
<input type="submit" value="Submit">
</form>
</div>
<script>
//Function to check if email is valid.
function validateEmail(userId) {
var re = /\S+#\S+/;
return re.test(email);
}
userId.onchange = validateEmail;
userId.onkeyup = validateEmail;
// Function to check if both passwords is same or not.
var password = document.getElementById("psw1"), psw2 = document.getElementById("psw2");
function validatePassword(){
if(psw1.value != psw2.value) {
psw2.setCustomValidity("Passwords Don't Match");
} else {
psw2.setCustomValidity('');
}
}
psw1.onchange = validatePassword;
psw2.onkeyup = validatePassword;
// Function for password strength meter
function PasswordMeter(password) {
if (password.length === 0) {
document.getElementById("msg").innerHTML = "";
return;
}
var matchedCase = new Array();
matchedCase.push("[$#$!%*#?&]"); // Special Charector
matchedCase.push("[0-9]"); // Numbers
matchedCase.push("[a-z]"); // Lowercase Alphabates
var ctr = 0;
for (var i = 0; i < matchedCase.length; i++) {
if (new RegExp(matchedCase[i]).test(password)) {
ctr++;
}
}
var color = "";
var strength = "";
switch (ctr) {
case 0:
case 1:
strength = "Weak: Keep going...";
color = "red";
break;
case 2:
strength = "Medium: A little better but add more..";
color = "blue";
break;
case 3:
strength = "Strong! Now that is good!";
color = "green";
break;
}
document.getElementById("msg").innerHTML = strength;
document.getElementById("msg").style.color = color;
}
</script>
</body>
</html>
So your regex is already checking that the password length is at least 8 characters. The only thing you have to do is to display a message if this length is below 8 characters. I overrided the 'strength' variable with the new message, but you could also display a new one.
<!DOCTYPE html>
<html>
<head>
<style>
</style>
</head>
<body>
<h3>Sign In</h3>
<div class="container">
<form action="/action_page.php">
<label for="userId">UserId:</label>
<input type="email" id="userId" name="email" pattern="[a-zA-Z0-9._%+-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,3}$" required>
<br>
<br>
<label for="psw1">Password:</label>
<input type="password" id="psw1" name="psw1" pattern="(?=.*[a-z])(?=.*[0-9])(?=.*[!##$%^&*_=+-]).{8,}" title="Must contain at least one number, one special character and at least 8 or more characters" onkeyup="PasswordMeter(this.value);"/><span id="msg"></span>
<br>
<br>
<label for="psw2">Password:</label>
<input type="password" id="psw2" name="psw2" pattern="(?=.*[a-z])(?=.*[0-9])(?=.*[!##$%^&*_=+-]).{8,}" title="Must contain at least one number, one special character and at least 8 or more characters" required>
<input type="submit" value="Submit">
</form>
</div>
<script>
//Function to check if email is valid.
function validateEmail(userId) {
var re = /\S+#\S+/;
return re.test(email);
}
userId.onchange = validateEmail;
userId.onkeyup = validateEmail;
// Function to check if both passwords is same or not.
var password = document.getElementById("psw1"), psw2 = document.getElementById("psw2");
function validatePassword(){
if(psw1.value != psw2.value) {
psw2.setCustomValidity("Passwords Don't Match");
} else {
psw2.setCustomValidity('');
}
}
psw1.onchange = validatePassword;
psw2.onkeyup = validatePassword;
// Function for password strength meter
function PasswordMeter(password) {
// here is the only part I modified
if (password.length === 0) {
document.getElementById("msg").innerHTML = "";
return;
} else if (password.length < 8) {
document.getElementById("msg").style.color = 'red';
document.getElementById("msg").innerHTML = "Your password must be at least 8 characters long";
return;
}
var matchedCase = new Array();
matchedCase.push("[$#$!%*#?&]"); // Special Charector
matchedCase.push("[0-9]"); // Numbers
matchedCase.push("[a-z]"); // Lowercase Alphabates
var ctr = 0;
for (var i = 0; i < matchedCase.length; i++) {
if (new RegExp(matchedCase[i]).test(password)) {
ctr++;
}
}
var color = "";
var strength = "";
switch (ctr) {
case 0:
case 1:
strength = "Weak: Keep going...";
color = "red";
break;
case 2:
strength = "Medium: A little better but add more..";
color = "blue";
break;
case 3:
strength = "Strong! Now that is good!";
color = "green";
break;
}
document.getElementById("msg").innerHTML = strength;
document.getElementById("msg").style.color = color;
}
</script>
</body>
</html>
I think what you want is to use different regular expressions for different strength passwords. Most regex engines have a feature called "lookarounds". They are basically assertions. I will provide you with an example using lookahead assertions.
var isEightCharactersLong = '(?=.{8,})';
var hasNumbers = '(?=.*[0-9])';
var hasLowerCase = '(?=.*[a-z])';
var hasUpperCase = '(?=.*[A-Z])';
// we're escaping the regex reserved characters using '\'
var hasSpecialCharacters = '(?=.*[!##\$%\^&])';
You can then use them to create more complex regular expressions by combining them:
// For ES6 with template strings
// 8 characters long AND has numbers AND (has lowercase OR has uppercase)
const weakPasswordRegex = new RegExp(
`^${isEightCharactersLong}${hasNumbers}(${hasLowerCase}|${hasUpperCase})$`);
// For lower ES versions
var weakPasswordRegex = new RegExp(
'^' + isEightCharactersLong + hasNumbers + '(' + hasLowerCase + '|' + hasUpperCase + ')$'
You can also extract the password strength measurement into a separate function:
function measurePasswordStrength(password) {
var weakPassword = new RegExp('<placeholder>');
var mediumPassword = new RegExp('<placeholder>');
var strongPassword = new RegExp('<placeholder>');
if (strongPassword.test(password)) return 3;
if (mediumPassword.test(password)) return 2;
if (weakPassword.test(password)) return 1;
return 0;
}
Then your PasswordMeter becomes a lot more readable and understandable:
function PasswordMeter(password) {
if (password.length === 0) {
document.getElementById("msg").innerHTML = "";
return;
}
var color = "";
var strength = "";
switch (measurePasswordStrength(password)) {
case 0:
case 1:
strength = "Weak: Keep going...";
color = "red";
break;
case 2:
strength = "Medium: A little better but add more..";
color = "blue";
break;
case 3:
strength = "Strong! Now that is good!";
color = "green";
break;
}
document.getElementById("msg").innerHTML = strength;
document.getElementById("msg").style.color = color;
}

Add user input to array // Javascript

This is the code I have so far. When the user enters a word into the input box, I want that word to be stored in an array via the Add Word button. Once a number of words have been entered, the user clicks the Process Word button and I want all the words in the array to appear. How would I do this? Also could someone also explain why when nothing is entered into the input box "field is empty" does not appear?
function begin() {
var word = "List of words";
var i = returnword.length
if (userinput.length === 0) {
word = "Field is empty"
}
document.getElementById('message2').innerHTML = word
while (i--) {
document.getElementById('message').innerHTML = returnword[i] + "<br/>" + document.getElementById('message').innerHTML;
}
}
function addword() {
var arrword = [];
returnword = document.getElementById('userinput').value;
arrword.push(returnword);
}
Addword()
Your function contains an array arrword. If you keep it inside your function it will be reset every time you call the function. You need to keep your array of words outside the function
Empty input
The empty input message should be shown when you click on the Add word button. Check the input and display a message if needed
Display word
You can simply use join() to display you array
var arrayOfWord = [];
var inputElement = document.getElementById('userinput');
var errorElement = document.getElementById('error');
var wordsElement = document.getElementById('words');
function addWord() {
errorElement.innerHTML = "";
var word = inputElement.value;
if (word.trim() === "")
errorElement.innerHTML = "Empty input";
else
arrayOfWord.push(word);
inputElement.value = "";
}
function process(){
words.innerHTML = arrayOfWord.join(' - ');
}
#error {
color: tomato;
}
#words {
color: purple;
}
Enter a word <input id="userinput" /><button onclick="addWord()">Add word</button>
<div id="error"></div>
<button onclick="process()">Process</button>
<div id="words"></div>
you can do something a bit clearer with jQuery! :)
if you handle the input with jquery you can write something like:
var arrWord = [] // your array
/* Attaching a click handler on your "Add Word" button that will
execute the function on user click */
$("#addWordButtonID").on("click", function () {
var wordTyped = $('#textInputID').val() // your var that collect userInput
if (wordTyped.length != 0) { // your if statement with length === 0 condition
arrWord.push(wordTyped) // adding word typed to the array
}
})
to add jquery to your html page, just add
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
in your html header
Hopefully you already have the right html. Then you can modify your script like below:
<script>
var arrword = [];
var returnword;
function begin() {
var word = "List of words";
var i = arrword.length;
if (arrword.length === 0) {
word = "Field is empty";
}
document.getElementById('message2').innerHTML = word;
while (i--) {
document.getElementById('message').innerHTML = arrword[i] + "<br/>" + document.getElementById('message').innerHTML;
}
}
function addword() {
returnword = document.getElementById('userinput').value;
arrword.push(returnword);
}
</script>
var arrword = [];
var returnword;
function begin() {
var word = "List of words";
var i = arrword.length;
if (arrword.length === 0) {
word = "Field is empty";
}
document.getElementById('message2').innerHTML = word;
while (i--) {
document.getElementById('message').innerHTML = arrword[i] + "<br/>" + document.getElementById('message').innerHTML;
}
}
function addword() {
returnword = document.getElementById('userinput').value;
arrword.push(returnword);
}
<button id="addWord" onclick="addword()">Add Word</button>
<button id="processWords" onclick="begin()">ProcessWords</button>
<input type="text" id="userinput" value=" " />
<div id="message2">
</div>
<div id="message">
</div>

how to change a javascript result from selectbox to textarea?

What I need to do I take the result from this code..
function genNumbers(listbox) {
var i, rannum;
for(i = 0; i < 1; i++) {
rannum = Math.random()*100000000;
rannum = Math.round(rannum);
if(listbox.options[i] == null) {
listbox.options[i] = new Option( rannum + "#domain.com", rannum + "#domain.com", 0, 0 );
} else {
listbox.options[i].value = rannum;
listbox.options[i].text = rannum + "#domain.com";
}
}
}
<form>
<select name="ranlist" size= "2" style="width:180px"></select><br><br>
<input type="button" value="Generate Random Email" onclick="genNumbers(this.form.ranlist)";>
And make the result appear in a text area. What I am using this for is to generate a random email address for people that dont have an email account when we sign up people in joomla. It all works except I need the result to show in a text area/textbox so i can copy paste it out and into the email field if needed.
Any helps would be great!
Cheers
Jimmy
Just set its value property:
textarea.value = 'foo';

Categories

Resources