How to create simple javascript/jquery client side captcha? - javascript

How to create simple javascript/jquery client side captcha?

Why don't you use reCAPTCHA ? It's free, very efficient, and provides accessibility functionnalities.

It can be done with HTML and a simple JavaScript code. Have a look at this:
function Captcha(){
var alpha = new Array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
'0','1','2','3','4','5','6','7','8','9');
var i;
for (i=0;i<6;i++){
var a = alpha[Math.floor(Math.random() * alpha.length)];
var b = alpha[Math.floor(Math.random() * alpha.length)];
var c = alpha[Math.floor(Math.random() * alpha.length)];
var d = alpha[Math.floor(Math.random() * alpha.length)];
var e = alpha[Math.floor(Math.random() * alpha.length)];
var f = alpha[Math.floor(Math.random() * alpha.length)];
var g = alpha[Math.floor(Math.random() * alpha.length)];
}
var code = a + ' ' + b + ' ' + ' ' + c + ' ' + d + ' ' + e + ' '+ f + ' ' + g;
document.getElementById("mainCaptcha").innerHTML = code
document.getElementById("mainCaptcha").value = code
}
function ValidCaptcha(){
var string1 = removeSpaces(document.getElementById('mainCaptcha').value);
var string2 = removeSpaces(document.getElementById('txtInput').value);
if (string1 == string2){
return true;
}else{
return false;
}
}
function removeSpaces(string){
return string.split(' ').join('');
}
.capt{
background-color:grey;
width: 300px;
height:100px;
}
#mainCaptcha{
position: relative;
left : 60px;
top: 5px;
}
#refresh{
position:relative;
left:230px;
width:30px;
height:30px;
bottom:45px;
background-image: url(rpt.jpg);
}
#txtInput, #Button1{
position: relative;
left:40px;
bottom: 40px;
}
<link rel="stylesheet" type="text/css" href="estilo.css" />
<script type="text/javascript" src="script.js"></script>
<body onload="Captcha();">
<div class="capt">
<h2 type="text" id="mainCaptcha"></h2>
<p><input type="button" id="refresh" onclick="Captcha();"/></p> <input type="text" id="txtInput"/>
<input id="Button1" type="button" value="Check" onclick="alert(ValidCaptcha());"/>
</div>
</body>

here you are ;)
var captchaText;
$(function() {
var pre = $('#captcha');
captchaText = pre.text();
pre.text('');
var lines = ['', '', '', '', '']
for (var ixLetter = 0; ixLetter < captchaText.length; ixLetter++) {
var letter = captchaText.substr(ixLetter, 1);
var letterLines = letters[letter];
for (var ix = 0; ix < 5; ix++) {
lines[ix] = lines[ix] + ' ' + letterLines[ix];
}
}
for (var ix = 0; ix < 5; ix++) {
pre.append(lines[ix] + '\n');
}
});
function check() {
if ($('#captchaCheck').val() == captchaText) {
alert('you are probably human');
} else {
alert('you probably made a mistake. Don\'t worry. To err is also human.');
}
}
var letters = {
h: [
'HH HH',
'HH HH',
'HHHHHH',
'HH HH',
'HH HH'
],
i: [
'II',
'II',
'II',
'II',
'II'
]
// etc
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<pre id="captcha">hi</pre> Please type what you see: <input id="captchaCheck" /> <input type="button" value="Check" onclick="check()" />

I agree with all the comments that client side captcha is fundamentally flawed, and I don't know know tough the hurdles have to be to mitigate any amount of spam...
To get an impression of what you're up against, though, check xRumer and GSA in action: YouTube: xEvil vs GSA Captcha Breaker
The software is also able to gather and decipher artificial intelligence such as security questions (i.e. what is 2+2?) often used by forums upon registration. Since the latest version of XRumer, the software is capable of collecting such security questions from multiple sources and is much more effective in defeating them.
wikipedia.org/wiki/XRumer
References:
How do spambots work? - Webmasters Stack Exchange (2010!)
BotDetect: Pure JavaScript CAPTCHA Validation Problems
So, caveats aside, here's a trivial alternative using HTML5 validation that's probably as ineffective as the other posts here! Presumably spambots would just add formnovalidate before submission, and would identify a honeypot field.
<form class="input">
<label for="number" class="title">
What is three plus four?
</label>
<br>
<input
name="number"
required="required"
pattern="(7|seven)"
oninvalid="this.setCustomValidity('Sorry, please enter the correct answer')"
oninput="this.setCustomValidity('')"
>
<!-- Bonus honeypot field, hidden from the user. The server should discard this response if it contains any input -->
<input name="decoy" style="display: none;" />
<input type="submit">
</form>

Client-Side captchas do not provide the protection a server-generated captcha would because the server can not check if the solved captcha is solved correctly.

That is not possible.
You could create something that looks like a CAPTCHA, but it would only run when it's not needed, i.e. when the page is shown in a browser. When it's needed it won't run, as the program trying to break in won't run the client side script.

function Captcha(){
var alpha = new Array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
'0','1','2','3','4','5','6','7','8','9');
var i;
for (i=0;i<6;i++){
var a = alpha[Math.floor(Math.random() * alpha.length)];
var b = alpha[Math.floor(Math.random() * alpha.length)];
var c = alpha[Math.floor(Math.random() * alpha.length)];
var d = alpha[Math.floor(Math.random() * alpha.length)];
var e = alpha[Math.floor(Math.random() * alpha.length)];
var f = alpha[Math.floor(Math.random() * alpha.length)];
var g = alpha[Math.floor(Math.random() * alpha.length)];
}
var code = a + ' ' + b + ' ' + ' ' + c + ' ' + d + ' ' + e + ' '+ f + ' ' + g;
document.getElementById("mainCaptcha").innerHTML = code
document.getElementById("mainCaptcha").value = code
}
function ValidCaptcha(){
var string1 = removeSpaces(document.getElementById('mainCaptcha').value);
var string2 = removeSpaces(document.getElementById('txtInput').value);
if (string1 == string2){
return true;
}else{
return false;
}
}
function removeSpaces(string){
return string.split(' ').join('');
}
<h1 This works pretty well. </h1>

if your purpose is to simply deflect most bots, you might be able to get away with a simple script that chooses 2 numbers at random and asks user to add them.

Try this:
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<script>
/* created dynamically by server when preparing the page */
// f function is on server and not known by bot and is random per result
// maybe bcrypt with a unique salt per request
var encodedResult = "f('X')";
var serverRenderedPositionSequence = [
[0,0],
[10,10],
[20,20],
[30,30],
[40,40],
[50,50],
[60,60],
[70,70],
[80,80],
[90,90],
[100,100],
[100,100],
[100,100],
[100,100],
[100,100],
[100,0],
[90,10],
[80,20],
[70,30],
[60,40],
[50,50],
[40,60],
[30,70],
[20,80],
[10,90],
[0,100]
];
window.index = 0;
window.move=function(but){
but.style.left = (serverRenderedPositionSequence[window.index][0]+"px");
but.style.top = (serverRenderedPositionSequence[window.index][1]+"px");
window.index++;
if(window.index<serverRenderedPositionSequence.length)
{
setTimeout(function(){
window.move(but);
},125);
}
}
window.onload=function(){
var but = document.getElementById("decoy-button");
window.index=0;
window.move(but);
};
function post()
{
// do something with
var xhrData= {
encodedResult:encodedResult,
result:document.getElementById('result').value
};
var postXhr=function(){ /* HTTP POST */}
// server checks if decoded "encoded result" is equal to the result (X here)
postXhr(xhrData);
}
</script>
</head>
<body>
<input id="result" type="text" value="Enter the message you see" />
<input id="test" onclick="post()" type="button" value="Post" />
<input id="decoy-button" type="button" value=" click me bot" style="width:0px;padding:0;position:absolute; left:0px; top:0px;" />
<input id="secret" type="button" onclick="window.index=0;move( document.getElementById('decoy-button'))" value="repeat sequence" />
</body>
</html>
Then the server would only use bcrypt to check if result is true.
Since the pattern matching requires dynamically observing the screen, it would cause some bots to fail. These would fail:
bots that click to post button immediately
bots that don't run javascript
bots that mis-click the decoy buttons
bots that can't understand the leap between coordinates in the sequence
for example when drawing X, it leaps from bot-right to top-right effectively drawing a vertical line on imaginary plane which may trick some bots easily
bots that use OCR with "fixed" screenshot timings
To further obfuscate any "canvas" hack, the server could add quick random bursts (with decreased latency between leaps) into the sequence such that resulting image would look unrecognizable but human will see what it writes between those random bursts.
To add one more depth, you can ask a math problem like
1+1
instead of just string.
But, when a bot memoizes the encoded result and re-sends it, the security is broken. So, have a "session" for client and not send any encoded result. Just the randomized sequence and check for result only by server-side. Of course the session also costs database time/space but at least website admin/editor does not see spam on the control panel of website.

please try this
<script type="text/javascript">
$('#submitcapt').click(function(){
var captval = "This will not do nothing";
$.ajax({
type : "POST",
url : "externals/reCaptcha/ajaxaction.php",
data : {loadval:captval},
success : function( msg ) {
if(msg=="1"){
}else{
}
}
})
});
</script>
In ajaxaction.php please put the following code
<?php
session_start();
$val=$_POST['loadval'];
$message= $_SESSION['random_number'];
if($val==$message) {
echo "1";
}else{
echo "2";
}
?>

$(document).ready(function() {
DrawCaptcha();
});
function refreshCap() {
DrawCaptcha();
}
function DrawCaptcha() {
var a = Math.ceil(Math.random() * 10) + '';
var b = Math.ceil(Math.random() * 10) + '';
var c = Math.ceil(Math.random() * 10) + '';
var d = Math.ceil(Math.random() * 10) + '';
var e = Math.ceil(Math.random() * 10) + '';
var f = Math.ceil(Math.random() * 10) + '';
var g = Math.ceil(Math.random() * 10) + '';
var code = a + ' ' + b + ' ' + ' ' + c + ' ' + d + ' ' + e + ' ' + f + ' ' + g;
var test = document.getElementById("ContentPlaceHolder1_txtCapcha").value = code;
alert(test);
}
function ValidCaptcha() {
var str1 = removeSpaces(document.getElementById('ContentPlaceHolder1_txtCapcha').value);
var str2 = removeSpaces(document.getElementById('ContentPlaceHolder1_txtinputCapcha').value);
if (str1 != str2) {
alert("Properly enter the Security code.");
document.getElementById('ContentPlaceHolder1_txtinputCapcha').focus() return false;
}
}
function removeSpaces(string) {
return string.split(' ').join('');
}

Related

The second response is not displayed in JavaScript?

I enter 2 x and z coordinates. And the response should display 2 responses.
1 answer — Sum to the number 600. 2 answer - Difference from the number 600.
I have only entered one response, and then to the second script, not the first.
https://www.w3schools.com/code/tryit.asp?filename=GMFS5UGR7FWC
<!DOCTYPE html>
<html>
<body>
<script>
var x, y, c;
var outputText;
function validate() {
// get the input
x = document.forms["input_form"]["aterm1"].value;
y = document.forms["input_form"]["aterm2"].value;
// validate a, b and c
if (x == 0) {} else {
// calculate
var a1 = x;
var a2 = y;
var a3 = 600;
var a4 = (a1 +++ a3);
var a5 = (a2 +++ a3);
outputText = "<h>" + a4 + ", " + a5 + "</h> ";
}
// output the result (or errors)
document.getElementById("1").innerHTML = outputText;
}
</script>
<script>
var x, y, c;
var outputText;
function validate() {
// get the input
x = document.forms["input_form"]["aterm1"].value;
y = document.forms["input_form"]["aterm2"].value;
// validate a, b and c
if (x == 0) {} else {
// calculate
var a1 = x;
var a2 = y;
var a3 = 600;
var a4 = (a1 --- a3);
var a5 = (a2 --- a3);
outputText = "<h>" + a4 + ", " + a5 + "</h> ";
}
// output the result (or errors)
document.getElementById("2").innerHTML = outputText;
}
</script>
<h type="x">X</h>
<h type="z">Z</h>
<form name="input_form" action="javascript:validate();">
<input type="text1" name="aterm1" size="5" required>
<input type="text2" name="aterm2" size="5" required>
<input type="submit" value="Готово">
</form>
<p type="ygol1" id="1">Первый угол</p>
<p type="ygol2" id="2">Второй угол</p>
</div>
</body>
</html>
You can't have two functions with the same name. The second one will overwrite the first one. If you need to perform two calculations, use two functions and perhaps a parent function to call them both.
function validate() {
sum();
difference();
}
function sum() {
// calculate the sum
}
function difference() {
// calculate the difference
}
and then in your form you call validate() which is a weird name by the way, for a function that doesn't validate anything. Use good names for your functions so they do what they say, it makes your code easy to read.
<form name="input_form" action="javascript:validate();">
<!DOCTYPE html>
<html>
<body>
<h type="x">X</h>
<h type="z">Z</h>
<form name="input_form" action="javascript:validate();">
<input type="text1" name="aterm1" size="5" required>
<input type="text2" name="aterm2" size="5" required>
<input type="submit" value="Готово">
</form>
<p type="ygol1" id="1">Первый угол</p>
<p type="ygol2" id="2">Второй угол</p>
<script>
function validate() {
// get the input
var x = document.forms["input_form"]["aterm1"].value;
var y = document.forms["input_form"]["aterm2"].value;
// output the result (or errors)
document.getElementById("1").innerHTML = "<h>" + (x + 600) + ", " + (y + 600) + "</h>";
document.getElementById("2").innerHTML = "<h>" + (x - 600) + ", " + (y - 600) + "</h>";
}
</script>
</body>
</html>
https://www.w3schools.com/code/tryit.asp?filename=GMFZ3DNB6ELT

Google Apps Script - Email stock notification?

Hi there!
I am a beginner both in JavaScript and in Google Sheets, but I am trying to find a way for Google Apps Script to basically scan the data I have brought in there from a Swedish Online Bank where they have some information about how the stocks go up and down.
Furthermore, I want to be notified by email when one of these on my list goes down by for example 5 % in a day.
I tried something like this:
let arrayRow = ["+" + 5.91 + "%", "+" + 5.22 + "%", "-" + 5.5 + "%"];
console.log(arrayRow);
function stockPricePlus() {
if (arrayRow >= "+" + 5 + "%") {
console.log("Yay! One of your stocks are going up by 5 % or more!");
}
}
function stockPriceMinus() {
if (arrayRow <= "-" + 5 + "%") {
console.log("Oh noes! One of your stocks are going down by 5 % or more!");
}
}
stockPricePlus();
stockPriceMinus();
And this works in my JavaScript file, but I am not quite sure how to make it pull the data continuously from the Google Sheets and run through them like a loop?
I found something on the internet that seemed to kind of do the job, but I also see that there are some missing parts in the code.
function sendEmails () {
var sheet = SpreadsheetApp.getActiveSheet();
var Price = sheet.getRange("B34:B").getValues();
var data = Price.getValues();
var results = [];
for (var i = 0; i < data.length; ++i) {
var row = data[i];
Logger.log(Price);
if (Price >= "+" + 5 + "%") {
MailApp.sendEmail("johnsmith#gmail.com", "Stock Price Alert from Stock Price Google Script", "One of your stocks are going up by 5 % or more!");
}
if (Price <= "-" + 5 + "%") {
MailApp.sendEmail("johnsmith#gmail.com", "Stock Price Alert from Stock Price Google Script", "One of your stocks are going down by 5 % or more!");
}
A ClientSide Timer for Collecting Periodic Stock Prices using GoogleFinance cell formulas
This code is a portion of code that I have used to check stocks. It has a timer function which runs clientside on your browser and you can adjust the sampling rate as you desire. I'd recommend no less that once every 5 minutes. That gives a good long time to get everything done. I also added a checkStats function which calculates percent change using the formula (max-min/max) * 100 and it compares this value with a value that you can set for each stock on the StockPrices page. It is also set up to send emails if the percent change is greater than a threshold and you can set. You can have as many stocks as you wish but you may need to adjust the sample rate if you try to get too many. You will have to add the email recipient address.
I have several other functions which chart the various stocks in different ways that I didn't include in this. I tried to keep this simple so I wouldn't be surprised if I have inadvently left some things out. Please note this script does not start automatically each day. In fact I hardly ever use it but I thought it would be an interesting thing to do and since then I've found the timer portion to be quite handy.
It's been my experience that GoogleFinance tags do not refresh regularly throughout the day. I've seen them not change at all for as long as 12 minutes while watching the stock prices change on another more elaborate system that runs on a personal computer.
datatimer.html:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<style>
#my_block{border:2px solid black;background-color:rgba(0,150,255,0.2);padding:10px 10px 10px 10px;}
#conv_block{border: 1px solid black;padding:10px 10px 10px 10px;}
.bttn_block{padding:5px 5px 0px 0px;}
.sndr_block {border:1px solid rgba(0,150,0,0.5);background-color:rgba(150,150,0,0.2);margin-bottom:2px;}
</style>
</head>
<body>
<form>
<div id="my_block" class="block form-group">
<div class="sndr_block">
<div id="myClock" style="font-size:20px;font-weight:bold;"></div>
<br />Timer Duration(minutes):
<br /><input id="txt1" type="text" size="4" class="action"/>
<select id="sel1" onChange="loadTxt('sel1','txt1');">
</select>
<div id="cntdiv"></div>
<br /><strong>Timer Controls</strong>
<div class="bttn_block"><input type="button" value="Start" name="startShow" id="startShow" onClick="startmytimer();changeData();" class="red" /></div>
<div class="bttn_block"><input type="button" value="Stop" name="stopTimer" id="stopTimer" class="red" /></div>
<div class="bttn_block"><input type="button" value="Single Ping" name="changedata" id="chgData" class="red" onClick="changeData();" /></div>
</div>
<div id="btn-bar">
<br /><input type="button" value="Exit" onClick="google.script.host.close();" class="green" />
</div>
</div>
</form>
<script>
var idx=1;
var myInterval='';
var cnt=0;
$(function() {
var select = document.getElementById('sel1');
select.options.length = 0;
for(var i=1;i<61;i++)
{
select.options[i-1] = new Option(i,i * 60000);
}
select.selectedIndex=4;
$('#startTimer').click(startmytimer);
$('#stopTimer').click(stopTimer);
$('#txt1').val(String(select.options[select.selectedIndex].value));
startTime();
});
function startTime(){
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById('myClock').innerHTML =
h + ":" + m + ":" + s;
var t = setTimeout(startTime, 500);
}
function checkTime(i){
if (i < 10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
function startmytimer(){
document.getElementById('cntdiv').innerHTML='<strong>Timer Started:</strong> ' + document.getElementById('myClock').innerHTML;
myInterval=setInterval(changeData, Number($('#txt1').val()));
}
function stopTimer(){
document.getElementById('cntdiv').innerHTML='Timer Stopped';
clearInterval(myInterval);
}
function loadTxt(from,to){
document.getElementById(to).value = document.getElementById(from).value;
}
function changeData(){
$('#txt1').css('background','#ffffcc');
google.script.run
.withSuccessHandler(updateDisplay)
.changeData();
}
function updateDisplay(t){
$('#txt1').css('background','#ffffff');
document.getElementById('cntdiv').innerHTML='<strong>Timer Running:</strong> Count= ' + ++cnt + ' <strong>Time:</strong> ' + t;
}
console.log('My Code');
</script>
</body>
</html>
Code.gs:
function onOpen(){
SpreadsheetApp.getUi().createMenu('MyTools')
.addItem('Show Timer SideBar', 'showTimerSideBar')
.addToUi();
}
//This is the function driven by the clientside timer trigger It also creates new data sheets for each day.
function changeData(){
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName('StockPrices');
var rg=sh.getRange(3,1,1,sh.getLastColumn());
var vA=rg.getValues();
var n=new Date();
var tmr=Utilities.formatDate(n, Session.getScriptTimeZone(), "HH:mm:ss");
var ts=Utilities.formatDate(n, Session.getScriptTimeZone(), "E-MMddyy-HHmmss");
var sheetTitle=Utilities.formatDate(n, Session.getScriptTimeZone(), "E-MMddyy");
vA[0][0]=ts;
if(isSheet(sheetTitle)){
ss.getSheetByName(sheetTitle).appendRow(vA[0]);
}else{
var sht=ss.insertSheet(sheetTitle);
var hA=sh.getRange(1,1,1,sh.getLastColumn()).getValues();
hA[0][0]="TimeStamp";
sht.appendRow(hA[0]);
sht.appendRow(vA[0]);
}
checkStats(sheetTitle);
return tmr;
}
function showTimerSideBar()
{
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName('StockPrices');
sh.getRange(5,2,1,sh.getLastColumn()-1).clearContent();//clears the sent row
var ui=HtmlService.createHtmlOutputFromFile('datatimer').setTitle('Javascript Trigger Generator');
SpreadsheetApp.getUi().showSidebar(ui);
}
function isSheet(sheetname){
var r=false;
var ss=SpreadsheetApp.getActive();
var allSheets=ss.getSheets();
for(var i=0;i<allSheets.length;i++){
if(allSheets[i].getName()==sheetname){
r=true;
break;
}
}
return r;
}
//This function checks stats and compares them to limits to determine if warning email messages should be sent
function checkStats(page) {
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName(page);
var rg=sh.getRange(1,2,sh.getLastRow(),sh.getLastColumn()-1);
var vA=rg.getValues();
var minA=vA[1].slice(0);
var maxA=vA[1].slice(0);
var pchA=[];
for(var i=2;i<vA.length;i++) {
for(var j=0;j<vA[i].length;j++) {
if(vA[i][j]>maxA[j]) {
maxA[j]=vA[i][j];
}
if(vA[i][j]<minA[j]) {
minA[j]=vA[i][j];
}
}
}
for(var i=0;i<minA.length;i++) {
pchA.push(Number(((maxA[i]-minA[i])/maxA[i]) * 100).toFixed(2));
}
var spsh=ss.getSheetByName('StockPrices');
var limitA=spsh.getRange(4,2,1,spsh.getLastColumn()-1).getValues();
var nameA=spsh.getRange(1,2,1,spsh.getLastColumn()-1).getValues();
var sentA=spsh.getRange(5,2,1,spsh.getLastColumn()-1).getValues();
var msgA=[];
for(var i=0;i<pchA.length;i++) {
if(pchA[i]>limitA[i] && sentA[i]!="SENT") {
msgA.push({name:nameA[i],change:pchA[i],limit:limitA[i],index:i});
}
}
if(msgA.length>0){
var html="<h1>Stocks Exceeding Change Limit</h1>";
var text='Stocks Exceeding Change Limit\n';
for(var i=0;i<msgA.length;i++) {
html+=Utilities.formatString('<br />Stock Name: <strong>%s</strong><br />Limit: <strong>%s</strong><br />Change: <strong>%s</strong><hr width="100%"/><br />', msgA[i].name,msgA[i].limit,msgA[i].change);
text+=Utilities.formatString('\nStock Name: %s\nLimit: %s\nChange: %s\n\n', msgA[i].name,msgA[i].limit,msgA[i].change);
sentA[msgA[i].index]="SENT";
}
//GmailApp.sendEmail(recipient, 'Stocks Exceeding Change Limit', text, {htmlBody:html})
spsh.getRange(5,2,1,spsh.getLastColumn()-1).setValues(sentA);
}
}
This is what the Stock Prices page looks like:
This is what a daily data page looks like:
And this is what the timer sidebar looks like:
Apps Script Documentation

Create a CAPTCHA verification form with JS (not server-side)

I want to create a captcha to stop spammers, but don not have the knowhow to use php and MySql to create server-side validation.
Any help would be appreciated...
I'd recommend to use a static "dummy.html" for the , because simple spammers will parse this and send an HTTP post request, bypassing the captcha validation.
For serious spammers, a client-side solution will never suffice.
Here's a basic implementation of what I mean:
https://jsfiddle.net/goyqdv7z/1/
<html>
<!-- action="invalid_captcha.html" IMPORTANT! SEE BELOW.! -->
<form method="post" id="idForm" action="invalid_captcha.html">
Form text goes here...<br/>
<div id="idCaptcha"/></div>
<input type="submit" value="Go!">
</form>
// 1. add a <div id="idCaptcha" into your <form action="invalid_caption.html" />
// 2. Replace the ULR
function CreateCaptcha() {
var a = Math.ceil(Math.random() * 9)+ '';
var b = Math.ceil(Math.random() * 9)+ '';
var c = Math.ceil(Math.random() * 9)+ '';
var d = Math.ceil(Math.random() * 9)+ '';
var captchaCode = a + ' ' + b + ' ' + ' ' + c + ' ' + d ;
document.getElementById("idCaptcha").innerHTML =
'<div >Please type the following figures: '+a+', '+b+', number '+c+' and number '+d+'</div>'
+'<input type="text" id="txtInputCaptcha" onkeyup="onChangeCaptcha();">'
+'<input type="hidden" id="idCaptchaHidden" value="'+captchaCode+'">'
;
}
CreateCaptcha();
function ValidCaptcha() { // valida los numeros ingresados
var str1 = removeSpaces(document.getElementById('idCaptchaHidden').value);
var str2 = removeSpaces(document.getElementById('txtInputCaptcha').value);
return (str1 == str2);
}
function removeSpaces(string) {
return string.split(' ').join('').split(',').join('');
}
function onChangeCaptcha(){
if(ValidCaptcha()){
var form = document.getElementById("idForm");
form.action = form.action.replace("invalid_captcha.html", "mailform.php");
form.style="background-color:#cfc;";
document.getElementById("idCaptcha").style='display:none;';
}
}
</html>
HTML:
<!DOCTYPE html>
<html>
<head><title>JS Captcha by Ian L. of Jafty.com</title>
<style>
body{
background-color: #430000;
}
</style>
</head>
<body>
<form name="review" ACTION="newpg.html" METHOD="POST" onsubmit="return checkform(this);">
<font color="#DD0000">Enter Code ></font> <span id="txtCaptchaDiv" style="background-color:#A51D22;color:#FFF;padding:5px"></span>
<input type="hidden" id="txtCaptcha" />
<input type="text" name="txtInput" id="txtInput" size="15" />
<input type="submit" value="Submit"/>
</form>
Javascript:
function checkform(theform){
var why = "";
if(theform.txtInput.value == ""){
why += "- Security code should not be empty.\n";
}
if(theform.txtInput.value != ""){
if(ValidCaptcha(theform.txtInput.value) == false){
why += "- Security code did not match.\n";
}
}
if(why != ""){
alert(why);
return false;
}
}
//Generates the captcha function
var a = Math.ceil(Math.random() * 9)+ '';
var b = Math.ceil(Math.random() * 9)+ '';
var c = Math.ceil(Math.random() * 9)+ '';
var d = Math.ceil(Math.random() * 9)+ '';
var e = Math.ceil(Math.random() * 9)+ '';
var code = a + b + c + d + e;
document.getElementById("txtCaptcha").value = code;
document.getElementById("txtCaptchaDiv").innerHTML = code;
// Validate the Entered input aganist the generated security code function
function ValidCaptcha(){
var str1 = removeSpaces(document.getElementById('txtCaptcha').value);
var str2 = removeSpaces(document.getElementById('txtInput').value);
if (str1 == str2){
return true;
}else{
return false;
}
}
// Remove the spaces from the entered and generated code
function removeSpaces(string){
return string.split(' ').join('');
}
This is just a simple one with no styling, however it works fine.
There are many automatic third party solutions for captchas such as ReCaptcha. But here you can find the explanationon how such technology actually works

Javascript cookie not saving when user input reaches a certain size

I am trying to Save user input from a textarea in a javascript cookie on the unload of a page and then read it back into a textarea when the user returns. The issue that I am having is the cookie is not saving when the user input reaches a certain length. It seems to be working fine with small strings.
Here is the html:
<html>
<head>
<title>Cookie Test</title>
<link rel="stylesheet" type="text/css" href="css/site.css">
</head>
<body class="full" onload="GetCookies()" onunload="WriteCookies()">
<div class="fullscreen-overlay" id="fullscreen_overlay">
<div class="fullscreen-container js-fullscreen-container">
<div class="textarea-wrap">
<textarea name="fullscreen-contents" id="fullscreen-contents"></textarea>
</div>
</div>
</div>
</body>
</html>
Javascript:
function WriteCookies() {
var d = new Date();
var n = document.getElementById('fullscreen-contents').value;
d.setDate(d.getDate() + 1);
document.cookie = "mainCookie = " + n + "; expires = " + d.toGMTString() + "";
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1);
if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
}
return "";
}
function GetCookies() {
document.getElementById('fullscreen-contents').value = getCookie('mainCookie');
}
Any ideas what could be going on? Thanks!
The max size of a cookie is 4093 bytes. Perhaps the long string is just eclipsing that limit. You could consider localStorage or sessionStorage instead
var text = document.getElementById('fullscreen-contents');
function saveText() {
localStorage.savedText = text.value;
console.log("saved");
}
function getText() {
if (localStorage.savedText) {
text.value = localStorage.savedText;
console.log("loaded");
}
}
Edited: Here is a fiddle

I have a JS script in my php file, and it does not seem to be executing

This started after I converted this same script which was previously laid out in PHP to JS (I tried to change all the syntax.)
I have tried running it how it is within the php file and it didn't work :
<html>
<head>
<title>Learn | A Level Scientist</title>
<link rel="shortcut icon" href="http://www.iconj.com/ico/f/0/f0ghi1ksdc.ico" type="image/x-icon" />
<style>
#menubar {;color:white;font-size:100%;padding-top:5px;padding-bottom:5px;
border-radius:5px;margin-top: 1%;margin-bottom:1%;margin-left:4%;margin-right:4%; background: rgba(0,73,126,0.6);}
span {margin-left:2.5%;margin-right:2.5%;}
#mainsection {background: rgba(0,73,126,0.6);color:white;margin-left:4%;margin-right:4%;border-radius:5px;padding-left:20px;padding-right:20px;padding-bottom:0.5%;text-align:center;}
body {background:radial-gradient(#00477C,#002E4F);}
#horizsep {width:100%;text-align:center;color:white;padding-top:0%;padding-bottom:0%;margin:0px}
#copyright{text-align:center;}
#welcomemsg {font-size:30px;margin:0px;padding:0px}
#surroundmid{font-size:26px; padding-bottom:160px;}
#start_learning:hover {width:155px;font-size:22px;color:white;background-color:#5288AB;border-width:0px;border-radius:5px;}
#tube_part {background-color:#DB2625;margin:0%;}
#you_part {margin:0%;color:black;border-radius:30px;text-align:center}
#fb_part {background-color:#3B5998;color:white;margin:0%;text-align:center}
#acebook_part {background-color:#3B5998;margin:0%}
a{color:white; underline:none}
a:hover {color: #4DB849 ; underline:none}
a:hover {color: #4DB849 ; underline:none}
a:hover {color: #4DB849 ; underline:none}
a:clicked {color: white; underline:none}
*.menubar {border-width:0px;border-radius:1px;background:rgba(0,0,0,0.1);color:white;}
*.menubar:hover{color:white;background-color:#5288AB;border-width:0px;border-radius:1px;}
#loginform {display:inline-block;margin:0px}
#chembutton {width:30%;height:10%;font-size:40px;color:white;background:rgba(17,214,118,0.3);border-width:0px;border-radius:5px;}
#chembutton:hover {width:32%;height:11%;font-size:45px;color:white;background:rgba(17,214,118,0.5);border-width:0px;border-radius:5px;}
#chembutton:active {width:33%;height:12%;font-size:45px;color:white;background:rgba(17,214,118,0.7);border-width:0px;border-radius:5px;}
#ytvid {margin-top:0%;margin-bottom:4.7%}
#video_navigation_next {width:40%;display:inline-block;}
#video_navigation_previous {width:40%;display:inline-block;}
#interface {display:block;width:900px;height:500px;background:rgba(0,46,79,0.4);margin:auto;border-radius:5px;margin-top:5px;margin-bottom:20px;vertical-align:top;}
#output{width:550px;border-radius:5px;height:450px;background:rgba(47,94,130,0.4);display:inline-block;margin:25px;vertical-align:top;font-size:18px}
#input{width:250px;border-radius:5px;height:450px;background:rgba(47,94,130,0.4);display:inline-block;margin:25px;margin-left:0px;vertical-align:top;}
#useranswer {margin-top:40px}
#helpsection {margin:10%}
</style>
</head>
<body>
<section>
<?php
include 'C:\xampp\htdocs\ALevelScientistTesting\menubar.php' ;
?>
<div id="mainsection">
<div id="welcomemsg"><strong><u> Working out Relative Formula/Molecular Masses </u></strong></div><br>
<div id="video_navigation_previous"><br><span id="nextvid"> <!-- <= Go to the Previous Exercise --> <span></div>
<div id="video_navigation_next"><br><span id="nextvid"> Go to the Next Exercise => <span></div>
<div id="interface">
<div id="output">
<?php
//echo 'The '.$CoMo.' : '.$SubName[$FormNo].' Has a Relative '.$FoMo.' Mass of : '.$x;
//echo '<br> Work out the Relative '.$FoMo.' Mass of the '.$CoMo.' : '.$SubName[$FormNo] ;
?>
<script type="text/javascript">
document.write('The Program got to here...');
//The following 3 Arrays store 3 things. 1) The Element names. 2) The element Symbols. 3) The Relative Atomic Masses of the Elements.
var Elements = new Array("Hydrogen","Lithium","Sodium","Potassium","Rubidium","Caesium","Francium","Beryllium","Magnesium","Calcium","Strontium","Barium","Radium","Scandium","Yttrium","Lanthanum","Actinium","Titanium","Zirconium","Halfnium","Rutherfordium","Vanadium","Niobium","Tantalum","Dubnium","Chromium","Molybdenum","Tungsten","Seaborgium","Manganese","Technetium","Rhenium","Bohrium","Iron","Ruthenium","Osmium","Hassium","Cobalt","Rhodium","Iridium","Meitnerium","Nickel","Palladium","Platinum","Darmstadtium","Copper","Silver","Gold","Roentgenium","Zinc","Cadmium","Mercury","Boron","Aluminum","Gallium","Indium","Thallium","Carbon","Silicon","Germanium","Tin","Lead","Nitrogen","Phosphorus","Arsenic","Antimony","Bismuth","Oxygen","Sulfur","Selenium","Tellurium","Polonium","Flourine","Chlorine","Bromine","Iodine","Astatine","Helium","Neon","Argon","Krypton","Xenon","Radon");
var ElementsSym = new Array("H","Li","Na","K","Rb","Cs","Fr","Be","Mg","Ca","Sr","Ba","Ra","Sc","Y","La","Ac","Ti","Zr","Hf","Rf","V","Nb","Ta","Db","Cr","Mo","W","Sg","Mn","Tc","Re","Bh","Fe","Ru","Os","Hs","Co","Rh","Ir","Mt","Ni","Pd","Pt","Ds","Cu","Ag","Au","Rg","Zn","Cd","Hg","B","Al","Ga","In","Tl","C","Si","Ge","Sn","Pb","N","P","As","Sb","Bi","O","S","Se","Te","Po","F","Cl","Br","I","At","He","Ne","Ar","Kr","Xe","Rn");
var ElementsRAM = new Array("1.0","6.9","23.0","39.1","85.5","132.9","223","9.0","24.3","40.1","87.6","137.3","226","45.0","88.9","138.9","227","47.9","91.2","178.5","261","50.9","92.9","180.9","262","52.0","95.9","183.8","266","54.9","98","186.2","264","55.8","101.1","190.2","277","58.9","102.9","192.2","268","58.7","106.4","195.1","271","63.5","107.9","197.0","272","65.4","112.4","200.6","10.8","27.0","69.7","114.8","204.4","12.0","28.1","72.6","118.7","207.2","14.0","31.0","74.9","121.8","209.0","16.0","32.1","79.0","127.6","209","19.0","35.5","79.9","126.9","210","4.0","20.2","39.9","83.8","131.3","222");
// The following 3 arrays store all of the molecule names and formulas, along with the subscripted versions of all of the formulas.
var CompoundsFormula = new Array("Al2O3","NH4N3","NH4ClO3","NH4ClO4","BaCrO4","BeCO3","C6H12N2O4Pt","CrO2F2","C3Cl3N3","GaP","LiCoO2","FeLiO4P","Li2SO4","OF2","KCaCl3","Ag2CrO4","AgBF4","H3NO3S","ZnBr2","Na2CO3","BaFe2O4","BrF5","CaCrO4","H2CO3","MgCO3","AgClO3","Ag3PO4","NaPO2H2","NaMnO4","Na2S2O8");
var CompoundsName = new Array("Aluminium oxide","Ammonium azide","Ammonium chlorate","Ammonium perchlorate","Barium chromate","Beryllium carbonate","Carboplatin","Chromyl fluoride","Cyanuric chloride","Gallium phosphide","Lithium cobalt oxide","Lithium iron phosphate","Lithium sulfate","Oxygen difluoride","Potassium calcium chloride","Silver chromate","Silver fluoroborate","Sulfamic acid","Zinc bromide","Sodium carbonate","Barium ferrite","Bromine pentafluoride","Calcium chromate","Carbonic acid","Magnesium carbonate","Silver chlorate","Silver orthophosphate","Sodium hypophosphite","Sodium permanganate","Sodium persulfate");
var SubCompoundsArray = new Array("Al<sub>2</sub>O<sub>3</sub>","NH<sub>4</sub>N<sub>3</sub>","NH<sub>4</sub>ClO<sub>3</sub>","NH<sub>4</sub>ClO<sub>4</sub>","BaCrO<sub>4</sub>","BeCO<sub>3</sub>","C<sub>6</sub>H<sub>1</sub><sub>2</sub>N<sub>2</sub>O<sub>4</sub>Pt","CrO<sub>2</sub>F<sub>2</sub>","C<sub>3</sub>Cl<sub>3</sub>N<sub>3</sub>","GaP","LiCoO<sub>2</sub>","FeLiO<sub>4</sub>P","Li<sub>2</sub>SO<sub>4</sub>","OF<sub>2</sub>","KCaCl<sub>3</sub>","Ag<sub>2</sub>CrO<sub>4</sub>","AgBF<sub>4</sub>","H<sub>3</sub>NO<sub>3</sub>S","ZnBr<sub>2</sub>","Na<sub>2</sub>CO<sub>3</sub>","BaFe<sub>2</sub>O<sub>4</sub>","BrF<sub>5</sub>","CaCrO<sub>4</sub>","H<sub>2</sub>CO<sub>3</sub>","MgCO<sub>3</sub>","AgClO<sub>3</sub>","Ag<sub>3</sub>PO<sub>4</sub>","NaPO<sub>2</sub>H<sub>2</sub>","NaMnO<sub>4</sub>","Na<sub>2</sub>S<sub>2</sub>O<sub>8</sub>");
// The following 3 arrays store all the compound names and formulas, along with the subscripted versions of all the formulas.
var MoleculesFormula = new Array("C15H20O4","C12H8","CH3CO2Na","C3H4O2","C60","C6H12O6","C5H9N1O4","C5H8O4","CN","H2O2","C13H18O2","C12H22O11","C14H14O3","C10H8","C14H18N2O5","C18H22O2","C3H3O3","C7H5N1O3S1","C5H6N2O2","C3H9N","C16H13Cl1N2O1","C19H16O4","C6H3N3O6","C8H8O3","C21H22N2O2","C6H14O6","C9H11N1O6","C10H20O1","C8N8O16","C6H6N12O12","C6H5NO2");
var MoleculesName = new Array("Abscisic acid","Acenaphthylene","Sodium acetate","Acroleic acid","Buckminsterfullerene","Fructose","Glutamate","Glutaric acid","Hydrogen Cyanide","Hydrogen Peroxide","Ibuprofen","Beta-Lactose","Naproxen","Naphthalene","Aspartame","Estrone","Pyruvate","Saccharin","Thymine","Trimethylamine","Diazepam","Warfarin","Trinitrobenzene","Vanillin","Strychnine","Sorbitol","Showdomycin","Menthol","Octanitrocubane","Hexanitrohexaazaisowurtzitane","Nitrobenzene");
var SubMoleculesArray = new Array("C<sub>1</sub><sub>5</sub>H<sub>2</sub><sub>0</sub>O<sub>4</sub>","C<sub>1</sub><sub>2</sub>H<sub>8</sub>","CH<sub>3</sub>CO<sub>2</sub>Na","C<sub>3</sub>H<sub>4</sub>O<sub>2</sub>","C<sub>6</sub><sub>0</sub>","C<sub>6</sub>H<sub>1</sub><sub>2</sub>O<sub>6</sub>","C<sub>5</sub>H<sub>9</sub>N<sub>1</sub>O<sub>4</sub>","C<sub>5</sub>H<sub>8</sub>O<sub>4</sub>","CN","H<sub>2</sub>O<sub>2</sub>","C<sub>1</sub><sub>3</sub>H<sub>1</sub><sub>8</sub>O<sub>2</sub>","C<sub>1</sub><sub>2</sub>H<sub>2</sub><sub>2</sub>O<sub>1</sub><sub>1</sub>","C<sub>1</sub><sub>4</sub>H<sub>1</sub><sub>4</sub>O<sub>3</sub>","C<sub>1</sub><sub>0</sub>H<sub>8</sub>","C<sub>1</sub><sub>4</sub>H<sub>1</sub><sub>8</sub>N<sub>2</sub>O<sub>5</sub>","C<sub>1</sub><sub>8</sub>H<sub>2</sub><sub>2</sub>O<sub>2</sub>","C<sub>3</sub>H<sub>3</sub>O<sub>3</sub>","C<sub>7</sub>H<sub>5</sub>N<sub>1</sub>O<sub>3</sub>S<sub>1</sub>","C<sub>5</sub>H<sub>6</sub>N<sub>2</sub>O<sub>2</sub>","C<sub>3</sub>H<sub>9</sub>N","C<sub>1</sub><sub>6</sub>H<sub>1</sub><sub>3</sub>Cl<sub>1</sub>N<sub>2</sub>O<sub>1</sub>","C<sub>1</sub><sub>9</sub>H<sub>1</sub><sub>6</sub>O<sub>4</sub>","C<sub>6</sub>H<sub>3</sub>N<sub>3</sub>O<sub>6</sub>","C<sub>8</sub>H<sub>8</sub>O<sub>3</sub>","C<sub>2</sub><sub>1</sub>H<sub>2</sub><sub>2</sub>N<sub>2</sub>O<sub>2</sub>","C<sub>6</sub>H<sub>1</sub><sub>4</sub>O<sub>6</sub>"," C<sub>9</sub>H<sub>1</sub><sub>1</sub>N<sub>1</sub>O<sub>6</sub>","C<sub>1</sub><sub>0</sub>H<sub>2</sub><sub>0</sub>O<sub>1</sub>","C<sub>8</sub>N<sub>8</sub>O<sub>1</sub><sub>6</sub>","C<sub>6</sub>H<sub>6</sub>N<sub>1</sub><sub>2</sub>O<sub>1</sub><sub>2</sub>","C<sub>6</sub>H<sub>5</sub>NO<sub>2</sub>");
//The following part is the section where the specific Formula will be randomly selected for the questions.
var MCselection = Math.floor(Math.random()*2);
document.write(MCselection);
if(MCselection == 0) {
var Formula = CompoundsFormula;
var Name = CompoundsName;
var SubName = SubCompoundsArray;
var CoMo = 'Compound';
var FoMo = 'Formula';
} else {
var Formula = MoleculesFormula;
var Name = MoleculesName;
var SubName = SubMoleculesArray;
var CoMo = 'Molecule';
var FoMo = 'Molecular';
}
var FormNo = Math.floor(Math.random()*30);
var Form = Formula[FormNo];
var FormName = Name[FormNo];
var FormSub = SubName[FormNo];
var ElementSub = new Array();
var FoRAM = new Array();
var ElemProduct = new Array();
// Note : This is the substring Syntax : ACTUAL_STRINGHERE.substr(start,length)
// Note : is_numeric will return TRUE if the substring in question is a number. False Otherwise.
var l = 0;
var y = 0;
// The following Code is going to strip away the elements and each corresponding number of moles
// of each element per unit compound/molecule into separate arrays.
while (l < Form.length)) {
if(Form.substr(l+1,1).toLowerCase()==Form.substr(l+1,1) || !isNaN(Form.substr(l+1,1))) {
if (!isNaN(Form.substr(l+1,1))) {
Element[y] = Form.substr(l,1);
if (!isNaN(Form.substr(l+2,1))) {
ElementSub[y] = Form.substr(l+1,2);
l++;
l++;
} else {
ElementSub[y] = Form.substr(l+1,1);
l++;
}
} else {
Element[y] = Form.substr(l,2);
if (!isNaN(Form.substr(l+2,1))) {
if (!isNaN(Form.substr(l+3,1))) {
ElementSub[y] = Form.substr(l+2,2);
l+=3;
} else {
ElementSub[y] = Form.substr(l+2,1);
l+=2;
}
} else {
ElementSub[y] = 1;
l++;
}
}
} else {
Element[y] = Form.substr(l,1);
ElementSub[y] = 1;
}
l++;
y++;
}
// this resets the value of $l to 0 so that it can be recycled for another while loop.
l = 0;
x = 0;
// The following Code Identifies The Different Elements Present in the Array.
while(x < Element.length) {
while(l < ElementsSym.length) {
if (ElementsSym[l]==Element[x]) {
FoRAM[x] = ElementsRAM[l];
}
l++;
}
l = 0;
x++;
}
// this also resets the value of $l to 0 so that it can be recycled for another while loop.
l = 0;
x = 0;
// This find the product of each element multiplied by the number of moles present per mole of the formula.
while(l<Element.length) {
ElemProduct[l] = FoRAM[l]*ElementSub[l];
// echo '<br>';
l++;
}
// This finds the total of all the molar elemental products b adding up the values in an array.
//x = array_sum(ElemProduct);
var n = 0;
var sum = 0;
while(n<ElemProduct.length) {
sum += ElemProduct[n];
n++;
}
document.write("The " + CoMo + " : " + SubName[FormNo] + " Has a Relative " + FoMo + " Mass of : " + sum );
// The following Line Presents the Information.
</script>
<script type="text/javascript">
</script>
<br><hr>
</div>
<div id="input">
<form id="useranswer">
Enter Your Answer Here<br>
<input type="text" id="useranswer"><br>
<input type="submit" id="usersubmit" value="Check Answer">
</form>
<div id="helpsection">
<hr><br>
Not sure what Relative Formula mass is? <br>
<a>Click Here.</a> <br>
Not sure what Relative Molecular mass is?<br>
<a>Click Here.</a>
<br>
<hr>
<br>
Haven't learned how to work this out yet? <br>
<a>Click Here.</a>
</div>
</div>
</div>
<hr>
<span id="copyright"> Copyright A Level Scientist 2014 | All rights reserved. <span>
</div>
</section>
</body>
</html>
When I run this code at the moment, the result looks like this :
http://postimg.org/image/6993cuaqb/
Can someone please explain to me what is wrong with the code at the moment ! Thank you :)
---EDIT /
This is my new script, it kind of works, but does not. If someone would kindly test it you may get an insight into what i'm talking about (NAN, Long decimals.). When you're testing it, refresh multiple times and look at what happens.
New Script :
<html>
<head></head>
<body>
<script>
//The following 3 Arrays store 3 things. 1) The Element names. 2) The element Symbols. 3) The Relative Atomic Masses of the Elements.
var Elements = new Array("Hydrogen","Lithium","Sodium","Potassium","Rubidium","Caesium","Francium","Beryllium","Magnesium","Calcium","Strontium","Barium","Radium","Scandium","Yttrium","Lanthanum","Actinium","Titanium","Zirconium","Halfnium","Rutherfordium","Vanadium","Niobium","Tantalum","Dubnium","Chromium","Molybdenum","Tungsten","Seaborgium","Manganese","Technetium","Rhenium","Bohrium","Iron","Ruthenium","Osmium","Hassium","Cobalt","Rhodium","Iridium","Meitnerium","Nickel","Palladium","Platinum","Darmstadtium","Copper","Silver","Gold","Roentgenium","Zinc","Cadmium","Mercury","Boron","Aluminum","Gallium","Indium","Thallium","Carbon","Silicon","Germanium","Tin","Lead","Nitrogen","Phosphorus","Arsenic","Antimony","Bismuth","Oxygen","Sulfur","Selenium","Tellurium","Polonium","Flourine","Chlorine","Bromine","Iodine","Astatine","Helium","Neon","Argon","Krypton","Xenon","Radon");
var ElementsSym = new Array("H","Li","Na","K","Rb","Cs","Fr","Be","Mg","Ca","Sr","Ba","Ra","Sc","Y","La","Ac","Ti","Zr","Hf","Rf","V","Nb","Ta","Db","Cr","Mo","W","Sg","Mn","Tc","Re","Bh","Fe","Ru","Os","Hs","Co","Rh","Ir","Mt","Ni","Pd","Pt","Ds","Cu","Ag","Au","Rg","Zn","Cd","Hg","B","Al","Ga","In","Tl","C","Si","Ge","Sn","Pb","N","P","As","Sb","Bi","O","S","Se","Te","Po","F","Cl","Br","I","At","He","Ne","Ar","Kr","Xe","Rn");
var ElementsRAM = new Array(1.0,6.9,23.0,39.1,85.5,132.9,223,9.0,24.3,40.1,87.6,137.3,226,45.0,88.9,138.9,227,47.9,91.2,178.5,261,50.9,92.9,180.9,262,52.0,95.9,183.8,266,54.9,98,186.2,264,55.8,101.1,190.2,277,58.9,102.9,192.2,268,58.7,106.4,195.1,271,63.5,107.9,197.0,272,65.4,112.4,200.6,10.8,27.0,69.7,114.8,204.4,12.0,28.1,72.6,18.7,207.2,14.0,31.0,74.9,121.8,209.0,16.0,32.1,79.0,127.6,209,19.0,35.5,79.9,126.9,210,4.0,20.2,39.9,83.8,131.3,222);
// The following 3 arrays store all of the molecule names and formulas, along with the subscripted versions of all of the formulas.
var CompoundsFormula = new Array("Al2O3","NH4N3","NH4ClO3","NH4ClO4","BaCrO4","BeCO3","C6H12N2O4Pt","CrO2F2","C3Cl3N3","GaP","LiCoO2","FeLiO4P","Li2SO4","OF2","KCaCl3","Ag2CrO4","AgBF4","H3NO3S","ZnBr2","Na2CO3","BaFe2O4","BrF5","CaCrO4","H2CO3","MgCO3","AgClO3","Ag3PO4","NaPO2H2","NaMnO4","Na2S2O8");
var CompoundsName = new Array("Aluminium oxide","Ammonium azide","Ammonium chlorate","Ammonium perchlorate","Barium chromate","Beryllium carbonate","Carboplatin","Chromyl fluoride","Cyanuric chloride","Gallium phosphide","Lithium cobalt oxide","Lithium iron phosphate","Lithium sulfate","Oxygen difluoride","Potassium calcium chloride","Silver chromate","Silver fluoroborate","Sulfamic acid","Zinc bromide","Sodium carbonate","Barium ferrite","Bromine pentafluoride","Calcium chromate","Carbonic acid","Magnesium carbonate","Silver chlorate","Silver orthophosphate","Sodium hypophosphite","Sodium permanganate","Sodium persulfate");
var SubCompoundsArray = new Array("Al<sub>2</sub>O<sub>3</sub>","NH<sub>4</sub>N<sub>3</sub>","NH<sub>4</sub>ClO<sub>3</sub>","NH<sub>4</sub>ClO<sub>4</sub>","BaCrO<sub>4</sub>","BeCO<sub>3</sub>","C<sub>6</sub>H<sub>1</sub><sub>2</sub>N<sub>2</sub>O<sub>4</sub>Pt","CrO<sub>2</sub>F<sub>2</sub>","C<sub>3</sub>Cl<sub>3</sub>N<sub>3</sub>","GaP","LiCoO<sub>2</sub>","FeLiO<sub>4</sub>P","Li<sub>2</sub>SO<sub>4</sub>","OF<sub>2</sub>","KCaCl<sub>3</sub>","Ag<sub>2</sub>CrO<sub>4</sub>","AgBF<sub>4</sub>","H<sub>3</sub>NO<sub>3</sub>S","ZnBr<sub>2</sub>","Na<sub>2</sub>CO<sub>3</sub>","BaFe<sub>2</sub>O<sub>4</sub>","BrF<sub>5</sub>","CaCrO<sub>4</sub>","H<sub>2</sub>CO<sub>3</sub>","MgCO<sub>3</sub>","AgClO<sub>3</sub>","Ag<sub>3</sub>PO<sub>4</sub>","NaPO<sub>2</sub>H<sub>2</sub>","NaMnO<sub>4</sub>","Na<sub>2</sub>S<sub>2</sub>O<sub>8</sub>");
// The following 3 arrays store all the compound names and formulas, along with the subscripted versions of all the formulas.
var MoleculesFormula = new Array("C15H20O4","C12H8","CH3CO2Na","C3H4O2","C60","C6H12O6","C5H9N1O4","C5H8O4","CN","H2O2","C13H18O2","C12H22O11","C14H14O3","C10H8","C14H18N2O5","C18H22O2","C3H3O3","C7H5N1O3S1","C5H6N2O2","C3H9N","C16H13Cl1N2O1","C19H16O4","C6H3N3O6","C8H8O3","C21H22N2O2","C6H14O6","C9H11N1O6","C10H20O1","C8N8O16","C6H6N12O12","C6H5NO2");
var MoleculesName = new Array("Abscisic acid","Acenaphthylene","Sodium acetate","Acroleic acid","Buckminsterfullerene","Fructose","Glutamate","Glutaric acid","Hydrogen Cyanide","Hydrogen Peroxide","Ibuprofen","Beta-Lactose","Naproxen","Naphthalene","Aspartame","Estrone","Pyruvate","Saccharin","Thymine","Trimethylamine","Diazepam","Warfarin","Trinitrobenzene","Vanillin","Strychnine","Sorbitol","Showdomycin","Menthol","Octanitrocubane","Hexanitrohexaazaisowurtzitane","Nitrobenzene");
var SubMoleculesArray = new Array("C<sub>1</sub><sub>5</sub>H<sub>2</sub><sub>0</sub>O<sub>4</sub>","C<sub>1</sub><sub>2</sub>H<sub>8</sub>","CH<sub>3</sub>CO<sub>2</sub>Na","C<sub>3</sub>H<sub>4</sub>O<sub>2</sub>","C<sub>6</sub><sub>0</sub>","C<sub>6</sub>H<sub>1</sub><sub>2</sub>O<sub>6</sub>","C<sub>5</sub>H<sub>9</sub>N<sub>1</sub>O<sub>4</sub>","C<sub>5</sub>H<sub>8</sub>O<sub>4</sub>","CN","H<sub>2</sub>O<sub>2</sub>","C<sub>1</sub><sub>3</sub>H<sub>1</sub><sub>8</sub>O<sub>2</sub>","C<sub>1</sub><sub>2</sub>H<sub>2</sub><sub>2</sub>O<sub>1</sub><sub>1</sub>","C<sub>1</sub><sub>4</sub>H<sub>1</sub><sub>4</sub>O<sub>3</sub>","C<sub>1</sub><sub>0</sub>H<sub>8</sub>","C<sub>1</sub><sub>4</sub>H<sub>1</sub><sub>8</sub>N<sub>2</sub>O<sub>5</sub>","C<sub>1</sub><sub>8</sub>H<sub>2</sub><sub>2</sub>O<sub>2</sub>","C<sub>3</sub>H<sub>3</sub>O<sub>3</sub>","C<sub>7</sub>H<sub>5</sub>N<sub>1</sub>O<sub>3</sub>S<sub>1</sub>","C<sub>5</sub>H<sub>6</sub>N<sub>2</sub>O<sub>2</sub>","C<sub>3</sub>H<sub>9</sub>N","C<sub>1</sub><sub>6</sub>H<sub>1</sub><sub>3</sub>Cl<sub>1</sub>N<sub>2</sub>O<sub>1</sub>","C<sub>1</sub><sub>9</sub>H<sub>1</sub><sub>6</sub>O<sub>4</sub>","C<sub>6</sub>H<sub>3</sub>N<sub>3</sub>O<sub>6</sub>","C<sub>8</sub>H<sub>8</sub>O<sub>3</sub>","C<sub>2</sub><sub>1</sub>H<sub>2</sub><sub>2</sub>N<sub>2</sub>O<sub>2</sub>","C<sub>6</sub>H<sub>1</sub><sub>4</sub>O<sub>6</sub>"," C<sub>9</sub>H<sub>1</sub><sub>1</sub>N<sub>1</sub>O<sub>6</sub>","C<sub>1</sub><sub>0</sub>H<sub>2</sub><sub>0</sub>O<sub>1</sub>","C<sub>8</sub>N<sub>8</sub>O<sub>1</sub><sub>6</sub>","C<sub>6</sub>H<sub>6</sub>N<sub>1</sub><sub>2</sub>O<sub>1</sub><sub>2</sub>","C<sub>6</sub>H<sub>5</sub>NO<sub>2</sub>");
//The following part is the section where the specific Formula will be randomly selected for the questions.
var MCselection = Math.floor(Math.random()*2);
if(MCselection === 0) {
var Formula = CompoundsFormula;
var Name = CompoundsName;
var SubName = SubCompoundsArray;
var CoMo = 'Compound';
var FoMo = 'Formula';
} else {
var Formula = MoleculesFormula;
var Name = MoleculesName;
var SubName = SubMoleculesArray;
var CoMo = 'Molecule';
var FoMo = 'Molecular';
}
var FormNo = Math.floor(Math.random()*30);
var Form = Formula[FormNo];
var FormName = Name[FormNo];
var FormSub = SubName[FormNo];
var ElementSub = new Array();
var FoRAM = new Array();
var ElemProduct = new Array();
var Element = new Array();
// Note : This is the substring Syntax : ACTUAL_STRINGHERE.substr(start,length)
// Note : is_numeric will return TRUE if the substring in question is a number. False Otherwise.
var l = 0;
var y = 0;
// The following Code is going to strip away the elements and each corresponding number of moles
// of each element per unit compound/molecule into separate arrays.
while (l <= Form.length) {
if((Form.substr(l+1,1).toLowerCase()==Form.substr(l+1,1)) || (!isNaN(Form.substr(l+1,1)))) {
if (!isNaN(Form.substr(l+1,1))) {
Element[y] = Form.substr(l,1);
if (!isNaN(Form.substr(l+2,1))) {
ElementSub[y] = Form.substr(l+1,2);
l++;
l++;
} else {
ElementSub[y] = Form.substr(l+1,1);
l++;
}
} else {
Element[y] = Form.substr(l,2);
if (!isNaN(Form.substr(l+2,1))) {
if (!isNaN(Form.substr(l+3,1))) {
ElementSub[y] = Form.substr(l+2,2);
l+=3;
} else {
ElementSub[y] = Form.substr(l+2,1);
l+=2;
}
} else {
ElementSub[y] = 1;
l++;
}
}
} else {
Element[y] = Form.substr(l,1);
ElementSub[y] = 1;
}
l++;
y++;
}
document.write(Element);
// this resets the value of $l to 0 so that it can be recycled for another while loop.
l = 0;
x = 0;
// The following Code Identifies The Different Elements Present in the Array.
while(x < Element.length) {
while(l < ElementsSym.length) {
if (ElementsSym[l]==Element[x]) {
FoRAM[x] = ElementsRAM[l];
}
l++;
}
l = 0;
x++;
}
// this also resets the value of $l to 0 so that it can be recycled for another while loop.
l = 0;
x = 0;
// This find the product of each element multiplied by the number of moles present per mole of the formula.
while(l<Element.length) {
ElemProduct[l] = FoRAM[l]*ElementSub[l];
// echo '<br>';
l++;
}
// This finds the total of all the molar elemental products b adding up the values in an array.
//x = array_sum(ElemProduct);
var n = 0;
var sum = 0;
while(n<ElemProduct.length) {
sum += ElemProduct[n];
n++;
}
document.write("<br> The " + CoMo + " : " + SubName[FormNo] + " Has a Relative " + FoMo + " Mass of : " + sum );
// The following Line Presents the Information.
</script>
</body>
</html>
can someone please point me in the right direction as to why this is happening. Thank you.
You have an error on your JS code. On line 125 you have close a bracket too "while (l < Form.length)) {". Fix it by deleting one and try the code

Categories