Why is `pieceOfText` undefined? - javascript

I am creating a little guessing game involving decrypting text, but there is a variable inside my JavaScript code that is not working correctly. This variable, called pieceOfText, is supposed to be equal to a random piece of text generated from an array of 3 pieces of encoded text. However, when I retrieve the value of said variable, it outputs undefined.
Here is the code I have now:
function randomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random * (max - min + 1)) + min;
} // defines the function that gets a random number
var text = ['smell', 'cat', 'jump']; // pieces of text to decrypt
var encryptedText = []; // the decrypted pieces of text.
for (var i = 0; i < text.length; i++) {
encryptedText.push(window.btoa(text[i]));
}
var pieceOfText = encryptedText[randomInt(0, 2)];
console.log(pieceOfText);
/* document.getElementById('para').innerHTML += " " + pieceOfText; */
function validateForm() {
var form = document.forms['game']['text'];
var input = form.value;
if (input == "") {
alert("Enter your answer within the input.");
return false;
} else if (!(/^[a-zA-Z0-9-]*$/.test(input))) {
alert("Your input contains illegal characters.");
return false;
} else if (input != window.atob(pieceOfText)) {
alert("Incorrect; try again.");
location.reload();
} else {
alert("Correct!");
location.reload();
}
}
<!DOCTYPE html>
<html>
<HEAD>
<META CHARSET="UTF-8" />
<TITLE>Decryption Guessing Game</TITLE>
</HEAD>
<BODY>
<p id="para">Text:</p>
<form name="game" action="get" onsubmit="return validateForm()">
Decrypt: <input type="text" name="text">
<input type="submit" value="Check!">
</form>
<SCRIPT LANGUAGE="Javascript">
</SCRIPT>
</BODY>
</html>
The line commented out is possibly preventing my guessing game from running properly because pieceOfText is set to undefined. I was currently doing some debugging at the time when I found this out. One question I found with a similar dilemma was more oriented towards ECMAScript 6 (I'm not sure if I'm using that), and others I found weren't even related to JavaScript. So, what caused this and how can I fix it?

You wrote Math.random instead of Math.random() (you forgot to actually call the function):
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Decryption Guessing Game</title>
</head>
<body>
<p id="para">Text:</p>
<form name="game" action="get" onsubmit="return validateForm()">
Decrypt: <input type="text" name="text">
<input type="submit" value="Check!">
</form>
<script>
function randomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
} // defines the function that gets a random number
var text = ['smell', 'cat', 'jump']; // pieces of text to decrypt
var encryptedText = []; // the decrypted pieces of text.
for (var i = 0; i < text.length; i++) {
encryptedText.push(window.btoa(text[i]));
}
var pieceOfText = encryptedText[randomInt(0, 2)];
console.log(pieceOfText);
/* document.getElementById('para').innerHTML += " " + pieceOfText; */
function validateForm() {
var form = document.forms['game']['text'];
var input = form.value;
if (input == "") {
alert("Enter your answer within the input.");
return false;
} else if (!(/^[a-zA-Z0-9-]*$/.test(input))) {
alert("Your input contains illegal characters.");
return false;
} else if (input != window.atob(pieceOfText)) {
alert("Incorrect; try again.");
location.reload();
} else {
alert("Correct!");
location.reload();
}
}
</script>
</body>
</html>

Related

What is missing from my discount code to make this work? Am I missing a variable?

I thought I had everything correct and I still can't seem to figure out why the function isn't working out the way it is supposed to. I have this issue where the code is having a reference error but I'm not sure how to define the function. I also put it through the W3 validator but that's not telling me anything.
<!DOCTYPE HTML>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>discount amount</title>
</head>
<body>
<script>
/* Input: purchase amount
* Processing: determine through if statements if they get a discount
* Output: final price after tax
*/
// Computes and returns a discounted purchase amount.
function getDiscountedAmount(purchase) {
var purchase =
parseInt(document.getElementById('purchase').value);
var dayOfWeek = new Date().getDay();
var output = document.querySelector("#output");
let rate;
if (purchase < 50) {
rate = 0.06;
} else if (purchase < 100 && [2, 3].includes(dayOfWeek)) {
rate = 0.06;
} else if (purchase < 500 && [2, 3].includes(dayOfWeek)) {
rate = 0.06;
}
let discount = purchase * rate;
return purchase - discount;
output.innerHTML = "$" + String(getDiscountedAmount(200));
}
</script>
Please enter your final price: <input type="text" id="purchase" size="5">
<br>
<button type="button" onclick="getDiscountedAmount(purchase)">discount?
</button>
<div id="output"></div>
</body>
</html>
The first line of your function already is wrong, you're trying to get a float number from nothing and you're overriding your input parameter to the function
var purchase = parseFloat();
Try:
purchase = parseFloat(purchase);
so that it uses your input parameter.
Also I'm not too sure about your date comparison dayOfWeek == (2, 3), I don't know if that works, I've never seen that before, I personally use [2, 3].includes(dayOfWeek)
And lastly your function returns a value but then you don't see that value anywhere, try using
console.log(getDiscountedAmount(200)) or whatever your price is
In terms of your input and output you want to use DOM manipulation to get the input and show the output.
If you want to see the value in your "output" then
var output = document.querySelector("#output");
output.innerHTML = "$" + String(getDiscountedAmount(200));
Would be a simple DOM mechanism, but it's not the cleanest
One more tip is to put your script tags lastly in the body, because you want all your HTML elements "defined" first before you try to access them
Altogether a cleaner version of your code:
<!DOCTYPE HTML>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>discount amount</title>
</head>
<body>
Please enter your final price: <input type="text" id="myInput" size="5" /><br />
<button type="button" id="myButton">discount?</button>
<div id="myOutput"></div>
<script>
var myInput = document.querySelector("#myInput");
var myOutput = document.querySelector("#myOutput");
var myButton = document.querySelector("#myButton");
myButton.onclick = function() {
// Computes and returns a discounted purchase amount.
var purchase = parseFloat(myInput.value);
var dayOfWeek = new Date().getDay();
var rate;
if (purchase < 50) {
rate = 0.06;
} else if (purchase < 100 && [2, 3].includes(dayOfWeek)) {
rate = 0.06;
} else if (purchase < 1000) {
rate = 0.025;
} else {
rate = 0.03;
}
let discount = purchase * rate;
var finalPrice = purchase - discount;
output.innerHTML = "$" + String(finalPrice);
};
</script>
</body>
</html>
I changed around some ID's and moved the onclick into your JavaScript for cleaner code overall, as we like to separate the HTML from the JS
When you load your script you get an Uncaught SyntaxError because you closed your function with two }. To fix this just delete line 31.
In your first line of the function you are using parseFloat(); wrong:
var purchase = parseFloat();
Do:
var purchase = parseFloat(purchase);
Than you need to get your input number.
getDiscountedAmount(purchase) in the onclick event doesn't work.
You can use this:
var purchase = document.getElementById("purchase").value; // get value from text field
purchase = parseFloat(purchase); // convert to float
In the end you have to do this to show the number in you output div:
let output = purchase - discount;
document.getElementById("output").innerText = output; // set discont into your output div
return output;
Here is your code and how i fixed it:
<!DOCTYPE HTML>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>discount amount</title>
<script>
/* Input: purchase amount
* Processing: determine through if statements if they get a discount
* Output: final price after tax
*/
// Computes and returns a discounted purchase amount.
function getDiscountedAmount(purchase) {
var purchase = document.getElementById("purchase").value; // get value from text field
purchase = parseFloat(purchase); // convert to float
var dayOfWeek = new Date().getDay();
var rate;
if (purchase < 50) {
rate = 0.06;
}
else if (purchase < 100 && dayOfWeek ==(2,3)) {
rate = 0.06;
}
else if (purchase < 1000) {
rate = 0.025;
}
else {
rate = 0.03;
}
let discount = purchase * rate;
let output = purchase - discount;
document.getElementById("output").innerText = output; // set discont into your output div
return output;
}
</script>
</head>
<body>
Please enter your final price: <input type="text" id="purchase" size="5"><be>
<button type="button" onclick="getDiscountedAmount()">discount?</button>
<div id="output"></div>
</body>
</html>
I didn't change your return statement and dayOfWeek because i don't know how you exactly want to use it.
Here is what you are looking for:
body{margin:0;padding:0;font-family:arial;background:rgb(30,30,30);height:100vh;width:100%}.wrapper{background:lightgrey;background:linear-gradient(318deg,rgba(217,123,123,1) 0%,rgba(135,249,255,1) 100%);width:80%;height:126px;position:relative;top:calc(50vh - 63px);left:10%;padding:3px;border-radius:12px}.content{background:rgb(80,80,80);background:rgba(0,0,0,.5);border-radius:10px;width:calc(100% - 24px);padding:12px}label{font-weight:700;color:#fff}input{width:calc(100% - 16px);margin-top:4px;padding:6px;border:2px solid #fff;border:2px solid rgba(0,0,0,.3);color:#fff;background:#fff;background:rgba(0,0,0,.5);border-radius:6px;font-size:14pt}::placeholder{color:#fff;color:rgba(255,255,255,.8)}input:focus{outline:none;border:2px solid #fff;border:3px solid rgba(0,0,0,.6);padding:5px}.output-container{display:inline-block;float:right;width:180px;padding:8px;color:#fff;background:#fff;background:rgba(0,0,0,.5);font-size:12pt;margin-top:4px;border-radius:6px;font-size:14pt}button{margin-top:4px;width:150px;border:0;border-radius:6px;padding:8px;background:gray;background:rgba(0,0,0,.6);color:#fff;font-weight:700;font-size:14pt;transition:0.25s ease}button:focus{outline:none;}button:hover{cursor:pointer;background:gray;background:rgba(0,0,0,.8)}#media only screen and (max-width:400px){.wrapper{width:calc(100% - 6px);height:auto;top:0;left:0;border-radius:0}.output-container,button{width:calc(50% - 12px)}}
<!DOCTYPE HTML>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>discount amount</title>
</head>
<body>
<div class='wrapper'>
<div class='content'>
<label>Please enter your final price:</label><input type="text" autocomplete="off" placeholder='Enter price...' id="purchase" size="5">
<button type="button" onclick="getDiscountedAmount()">See discount</button>
<div class='output-container'>Total: <span id='output'>--</span></div>
</div>
</div>
<script>
//Get the output element
outputEl = document.getElementById("output");
function getDiscountedAmount() {
//Gets the value of your input
var purchase = parseFloat((document.getElementById('purchase').value).replace(/[^\d]/g,""));
var dayOfWeek = new Date().getDay();
var rate;
if (purchase < 50) {
rate = 0.06;
} else if (purchase < 100 && [2, 3].includes(dayOfWeek)) {
rate = 0.06;
} else if (purchase < 500 && [2, 3].includes(dayOfWeek)) {
rate = 0.06;
}
else {
rate = 0.03;
}
let discount = purchase * rate;
let output = purchase - discount;
//Checks if output is a number.
if(isNaN(output)){
output = 'Not a number!';
} else{
output = '$' + output;
}
//Puts the output inside of your "output" <div>
outputEl.textContent = output;
}
</script>
</body>
</html>

How to add an animation gif to a javascript program

I am very new to the world of coding and I am in a coding bootcamp learning about JavaScript. We created a number guessing game and I am trying to add an animation that will run after the correct answer is entered. I have googled a few times trying to find the answer, but I was looking to see if there is an easier way. I have included a copy of the program below. If I wanted an animation to appear after the correct answer is entered, how could I do that?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Number Guessing Game</title>
</head>
<body style='background-color:black'>
<h1>Number Guessing Game</h1>
<button type="button" onclick="runGame()">Start Game</button>
<script>
function runGame() {
let guessString ='';
let guessNumber = 0;
let correct = false;
let numTries = 0;
const randomNumber = Math.random() * 100;
const randomInteger = Math.floor(randomNumber);
const target = randomInteger + 1;
do {
guessString = prompt('I am thinking of a number in the range 1 to 100.\n\nWhat is the number?');
guessNumber = +guessString;
numTries += 1;
correct = checkGuess(guessNumber, target, numTries);
} while (!correct);
alert('You got it! The number was ' + target + '.\n\nIt took you ' + numTries + ' tries to guess correctly.');
}
function checkGuess(guessNumber, target, numTries) {
let correct = false;
if (isNaN(guessNumber)) {
alert('Alright smarty pants!\n\nPlease enter a number in the 1-100 range.');
} else if ((guessNumber < 1) || (guessNumber > 100)) {
alert('Please enter an integer in the 1-100 range.');
} else if (guessNumber > target) {
alert('Your number is too large!\n\nGuess Number: ' + numTries + '.');
} else if (guessNumber < target) {
alert('Your number is too small!\n\nGuess Number: ' + numTries + '.');
} else {
correct = true;
}
return correct;
}
</script>
</body>
</html>
To be able do that you need to learn DOM Manipulation.
Here is a simple example :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Number Guessing Game</title>
</head>
<body style='background-color:black'>
<h1>Number Guessing Game</h1>
<button type="button" onclick="runGame()">Start Game</button>
<script>
function runGame() {
let guessString ='';
let guessNumber = 0;
let correct = false;
let numTries = 0;
const randomNumber = Math.random() * 100;
const randomInteger = Math.floor(randomNumber);
const target = randomInteger + 1;
do {
guessString = prompt('I am thinking of a number in the range 1 to 100.\n\nWhat is the number?');
guessNumber = +guessString;
numTries += 1;
correct = checkGuess(guessNumber, target, numTries);
} while (!correct);
alert('You got it! The number was ' + target + '.\n\nIt took you ' + numTries + ' tries to guess correctly.');
// add your gif to the dom
// create an img element
const img = document.createElement("img")
// set the source of the gif
img.src = "https://i0.wp.com/badbooksgoodtimes.com/wp-content/uploads/2017/12/plankton-correct-gif.gif?fit=400%2C287"
// add the img element to the dom
// in this case we are gonna add it after the 'start game' button, so
// select the button element
const btn = document.querySelector("button")
// insert the img element after the button
btn.parentNode.insertBefore(img, btn.nextSibling);
}
function checkGuess(guessNumber, target, numTries) {
let correct = false;
if (isNaN(guessNumber)) {
alert('Alright smarty pants!\n\nPlease enter a number in the 1-100 range.');
} else if ((guessNumber < 1) || (guessNumber > 100)) {
alert('Please enter an integer in the 1-100 range.');
} else if (guessNumber > target) {
alert('Your number is too large!\n\nGuess Number: ' + numTries + '.');
} else if (guessNumber < target) {
alert('Your number is too small!\n\nGuess Number: ' + numTries + '.');
} else {
correct = true;
}
return correct;
}
</script>
</body>
</html>
keep going and good luck.

User guesses a number from 1-1000 using functions

I am trying to make a program that prompts the user to guess a number from 1 to 1000. The program generates a random number and then the user has to guess the number until they get it right. The program alerts the user if their guess is too low or too high. Upon entering the right number, they are congratulated and asked if they want to run it again. I have read my book and even looked online for guidance, but against my best effort all it does is display the text field with the calculate button...no window messages or anything. Please help as I am stumped. This is what I have so far:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Assignment 9.25</title>
<script type="text/javascript">
var inputField;
var guess;
var calculateButton;
function startGame() {
window.alert("Guess a number between 1 and 1000 in the text field.");
calculateButton = document.getElementById("calculate");
//calculateButton.disable = true;
guessNum();
}
function randomNum(random) {
return Math.floor(1 + (Math.random() * 999));
}
function guessNum() {
inputField = document.getElementById("entry");
guess = parseFloat(inputField.value);
while (randomNum(random) != guess) {
if (randomNum(random) > guess) {
window.alert("Too low. Try again.");
}
else if (randomNum(random) < guess) {
window.alert("Too high. Try again.");
}
}
window.alert("Congratulations. You guessed the number!");
playAgain();
}
function playAgain() {
var again = window.prompt("Enter 'yes' to play again");
if (again == "yes") {
Start();
calculateButton.disabled = false;
else if (again == "no") {
alert ("Thank you for playing! Goodbye!")
calculateButton.disabled = true;
}
}
function Start() {
var calculateButton = document.getElementById("calculate");
calculateButton.addEventListener( "click", startGame, false );
}
window.addEventListener("load", Start, false);
</script>
</head>
<body>
<form action="#">
<div>
<label>Your guess here:
<input id="entry" type="number">
</label>
<br>
<input id="calculate" type="button" value="Calculate">
</div>
</form>
</body>
</html>
There is a } missing in line 45
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Assignment 9.25</title>
<script type="text/javascript">
var inputField;
var guess;
var calculateButton;
function startGame() {
window.alert("Guess a number between 1 and 1000 in the text field.");
calculateButton = document.getElementById("calculate");
//calculateButton.disable = true;
guessNum();
}
function randomNum(random) {
return Math.floor(1 + (Math.random() * 999));
}
function guessNum() {
inputField = document.getElementById("entry");
guess = parseFloat(inputField.value);
while (randomNum(random) != guess) {
if (randomNum(random) > guess) {
window.alert("Too low. Try again.");
}
else if (randomNum(random) < guess) {
window.alert("Too high. Try again.");
}
}
window.alert("Congratulations. You guessed the number!");
playAgain();
}
function playAgain() {
var again = window.prompt("Enter 'yes' to play again");
if (again == "yes") {
Start();
calculateButton.disabled = false;
}
else if (again == "no") {
alert ("Thank you for playing! Goodbye!")
calculateButton.disabled = true;
}
}
function Start() {
var calculateButton = document.getElementById("calculate");
calculateButton.addEventListener( "click", startGame, false );
}
window.addEventListener("load", Start, false);
</script>
</head>
<body>
<form action="#">
<div>
<label>Your guess here:
<input id="entry" type="number">
</label>
<br>
<input id="calculate" type="button" value="Calculate">
</div>
</form>
</body>
</html>
Jquery way if you mind
var a = Math.floor((Math.random() * 100) + 1);
$(document).ready(function(){
$('#numberrandom').text(a);
});
$('#calculate').bind('click',function(){
entrynumber=$('#entry').val();
if(entrynumber > a){
alert('Your number is higher than it')
}
else if(entrynumber < a){
alert('Your number is lower than it')
}
else if(entrynumber == a){
alert('nice you won')
location.reload();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<form action="#">
<div>
<label>Your guess here:
<input id="entry" type="number">
</label>
<br>
<input id="calculate" type="button" value="Calculate">
<span>generated number: </span><span id='numberrandom'></span>
</div>
</form>
</body>

Can't get JQuery to append some html and a value

I'm trying to create a script to keep a history track of three for a random number generator. (this is all for practice to take more advance approach) but I for some reason cannot get jQuery to Append a new html table/row after the code starts executing from a different JS file. however everything seems to go according to plan besides the part when I am trying to add the row into the table. I have a jsfiddle here:
http://jsfiddle.net/e3ey2a3s/2/
Here is my code however:
convert.js (the generator)
var min, max, setDol = false,
pArry = [];
function chooseRandom() {
min = prompt('whats the max value?', 'max');
max = prompt('whats the min value?', 'min');
return convertType(min, max);
}
function convertType(min, max) {
if (typeof min === 'string' || typeof max === 'string') {
document.getElementById('convert').innerHTML = "converting strings to numbers..."
parseInt(min);
parseInt(max);
}
return getRandom(min, max);
}
function getRandom(min, max) {
if (isNaN(min) || isNaN(max)) {
borked();
} else {
return amtFixed(Math.random() * (max - min) + min);
}
}
function amtFixed(amt) {
if (amt >= 0 && amt <= 10) {
document.getElementById('text').innerHTML = "Our number is " + amt + " which is between 0 and 10";
} else if (amt >= 11 && amt <= 20) {
document.getElementById("text").innerHTML = "Our number is " + amt + " which is between 11 and 20";
} else {
document.getElementById("text").innerHTML = "Our number is " + amt + " which is greater than 20. huh.";
}
var fixed = Number(amt).toFixed(2);
return convertFix(fixed);
};
function convertFix(fixed) {
if (typeof fixed === 'string') {
fixed = (fixed / 1);
document.getElementById("fixed").innerHTML = typeof fixed + " " + fixed + " converted down to two decimals.";
setDol = confirm("Convert our amount to a dollar amount?");
} else {
console.log('Failed to convert...');
}
return success(fixed);
};
function borked() {
var broke = false;
alert("You must not of entered a proper number... That sucks :/");
var broke = confirm("Do you want to retry?");
if (broke) {
return chooseRandom();
} else {
return document.getElementById("text").innerHTML = "I r broked :(";
}
}
function success(num) {
var amtHist = [];
if (setDol) {
$("#price").append('$' + num + ' Set fixed to a dollar amount!');
pArry.push(num);
return buildHistory(pArry);
} else {
$("#price").empty().append("Our fixed value is: " + num);
pArry.push(num);
return buildHistory(pArry);
}
}
After this script finishes up success() send the finished array over to my data.js function buildHistory() which looks like this:
buildHistory = function(arr) {
var t, i, _this = this,
numEls = 0,
a = arr;
var objLen = holdObj.History.length;
table = $('table.history');
//Let's do our loops to check and set history data
//We need to get our history data so we can make sure not to re print old data.
for (t = 0; t <= objLen; t++) {
for (i = 0; i < a.length; i++) {
x = objLen[t];
if ($.inArray(x, a) === -1) {
//Alright now we build onto the history table
$('table.history').append('<tr><td>' + a[i] + '</td></tr>');
var cell = table.find('td');
cell.addClass('hist' + numEls);
numEls++;
holdObj.History.push(a[i]);
} else {
break;
}
}
}
// Let's remove the oldest value once the table exceeds 3 or 4.
if (objLen > 3 && numEls > 3) {
var tmp = table.find('hist_3');
table.remove(tmp);
holdObj.History.pop();
}
}
This is all still in the makes so nothing is really finalized here, I am probably just overlooking a simple solution.
Here is my HTML:
<html>
<head>
<script type="text/javascript" src="../source/libs/jQuery-1.8.3.min.js"></script>
<title>Index</title>
</head>
<body>
<p>This is just some filler content lol.</p>
<p>Let's run some scripts! Click the buttons!</p>
<div class="math">
<p id="convert"></p>
<p id="text"></p>
<p id="fixed"></p>
<p id="price"></p>
<table id="history">
<tr>
<th>History</th>
</tr>
<tr>
<td id="hist"> Value #1</td>
</tr>
</table>
</div>
<button class="scrBtn">Click to start Script</button>
<div id="date"></div>
<button class="dateBtn">Get Date</button>
<div class="person">
<div class="pTitle">
<div class="pBody">
<div class="fName">Name: </div>
<div class="age">Age: </div>
<div class="height">Height: </div>
<div class="eyecolor">Eye Color: </div>
<div class="sex">Sex: </div>
This is where our person should go.
</div>
</div>
</div>
<a href="view/Form/personForm.html">
<button class="pBtn">Get Info</button>
</a>
<div class="bRowLeft">test
</div>
<div class="tRowLeft">test
</div>
</body>
<script type="text/javascript" src="../source/model/data.js"></script>
<script type="text/javascript" src="../source/model/convert.js"></script>
<script type="text/javascript" src="../source/model/button.js"></script>
<link rel="stylesheet" type="text/css" href="css/styles.css">
</html>
Sorry for such a long post but I am trying to explore as much as I can.
(The code is activated via jQuery with button.js)
$(document).ready(function() {
$('.scrBtn').click(function() {
chooseRandom();
});
});
Thanks again, let me know if anymore information is needed.
$('table.history') - you dont have a <table class="history"> element.
Try this:
table = $("#history");
and same where you append.

Is it possible to use another button to tell me the last alert?

I am looking to have two buttons and one auto generates a random string in an alert and I want another user to be able to go and enter the code in a text box and tell them if its valid or not.
First is this possible? Second, for someone new to JavaScript is this difficult?
Here is the current code I am using right now.
<script language="javascript" type="text/javascript">
function randomString() {
var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
var string_length = 5;
var randomstring = '';
for (var i=0; i<string_length; i++) {
var rnum = Math.floor(Math.random() * chars.length);
randomstring += chars.substring(rnum,rnum+1);
}
return randomstring;
}
</script>
<script>
function myFunction()
{
alert(randomString());
}
</script>
Thanks1
how about that one:
----------- file: index.html -----------
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Captcha Test</title>
<script src="test.js"></script>
</head>
<body onload="loadCaptcha('captcha-region')">
<div id="captcha-region"
style="text-indent: 10px; background: #fffccc"></div>
<label for="captcha"> Re-type text: </label>
<input id="captcha" type="text" value="" />
<input type="button" value="Submit"
onclick="checkCaptcha('result-region')" />
<input type="button" value="Reload"
onclick="loadCaptcha('captcha-region')" />
<div id="result-region"></div>
</body>
</html>
--------- file: test.js -----------------
function randomInt (range) {
return Math.floor(Math.random() * range);
}
function randomPos (s) {
return randomInt(s.length);
}
function randomChar (s) {
return s.charAt(randomPos(s));
}
var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
function randomString () {
var s = '',
i = 0;
while (i++ < 5) {
s += randomChar(chars);
}
return s;
}
function htmlInsert (id, htmlData) {
document.getElementById(id).innerHTML = htmlData;
}
var captcha;
function loadCaptcha (captchaRegion) {
captcha = randomString();
htmlInsert(captchaRegion, '<h1>' + captcha + '</h1>');
}
function checkCaptcha (resultRegion) {
var okText = (captcha === document.getElementById('captcha').value)
? '<span style="color: yellowgreen"> ok </span>'
: '<span style="color: orange"> not ok </span>';
htmlInsert(resultRegion, '<h2>Typed text: ' + okText + '</h2>');
}
This basically is kinda captcha demo, maybe that contains some good parts..
You may want to put index.html & test.js in a directory of your liking (no local web server needed), then from inside that directory execute: "firefox index.html" and you're good to go..
What do you think?

Categories

Resources