Over my head with javascript. I'm trying to get the cards to shuffle when clicking next.
Currently, it moves forward with one random shuffle and stops. Back and forward buttons then no longer work at that point.
Please help—many thanks.
When I'm lost and unsure what sample of the code to pinpoint, the captions go up to 499. The sample is also here: https://rrrhhhhhhhhh.github.io/sentences/
Very new to javascript. So any help is greatly appreciated. Very open to better ways to achieve this???
How I have it set up:
HTML:
var r = -1;
var mx = 499; // maximum
var a = new Array();
function AddNumsToDict(){
var m,n,i,j;
i = 0;
j = 0;
while (i <= 499)
{
m = (500 * Math.random()) + 1;
n = Math.floor(m);
for (j=0;j<=499;j++)
{
if (a[j] == (n-1))
{
j = -1;
break;
}
}
if (j != -1)
{
//a.push(n-1);
a[i] = (n-1);
i++;
j=0;
}
}
return;
}
function startup()
{
writit('SENTENCES<br><br><br>Robert Grenier', 'test');
SetCookie("pg", -1);
AddNumsToDict();
}
function SetCookie(sName, sValue)
{
document.cookie = sName + "=" + escape(sValue) + ";"
}
function GetCookie(sName)
{
// cookies are separated by semicolons
var aCookie = document.cookie.split("; ");
for (var i=0; i < aCookie.length; i++)
{
// a name/value pair (a crumb) is separated by an equal sign
var aCrumb = aCookie[i].split("=");
if (sName == aCrumb[0])
return unescape(aCrumb[1]);
}
// a cookie with the requested name does not exist
return null;
}
function doBack(){
//var oPrev = xbElem('prev');
//var oNxt = xbElem('nxt');
//if ((oNxt) && (oPrev))
//{
var num = GetCookie("pg");
if (num == mx){ //maximum
SetCookie("pg",parseInt(num) - 1);
num = GetCookie("pg");
}
// oNxt.disabled = false;
// if (num <= 1){
// oPrev.disabled = true;
// }
if (num >= 1){
num--;
writit(Caption[a[num]], 'test');
SetCookie("pg",num);
}
//}
}
function doNext(){
//var oPrev = xbElem('prev');
//var oNxt = xbElem('nxt');
// if ((oNxt) && (oPrev))
// {
var num = GetCookie("pg");
// if (num > -1){
// oPrev.disabled = false;
// }
// else{
// oPrev.disabled = true;
// }
// if (num >= parseInt(mx)-1){ //maximum - 1
// oNxt.disabled = true;
// }
// else {
// oNxt.disabled = false;
// }
if (num <= parseInt(mx)-2){
num++;
writit(Caption[a[num]],'test');
SetCookie("pg",num);
}
// }
}
function writit(text,id)
{
if (document.getElementById)
{
x = document.getElementById(id);
x.innerHTML = '';
x.innerHTML = text;
}
else if (document.all)
{
x = document.all[id];
x.innerHTML = text;
}
else if (document.layers)
{
x = document.layers[id];
l = (480-(getNumLines(text)*8))/2;
w = (764-(getWidestLine(text)*8))/2;
text2 = '<td id=rel align="center" CLASS="testclass" style="font:12px courier,courier new;padding-left:' + w.toString() + 'px' + ';padding-top:' + l.toString() + 'px' + '">' + text + '</td>';
x.document.open();
x.document.write(text2);
x.document.close();
}
}
function getNumLines(mystr)
{
var a = mystr.split("<br>")
return(a.length);
}
function getWidestLine(mystr)
{
if (mystr.indexOf(" ") != -1)
{
re = / */g;
mystr = mystr.replace(re,"Z");
//alert(mystr);
}
if (mystr.indexOf("<u>") != -1)
{
re = /<u>*/g;
mystr = mystr.replace(re, "");
re = /<\/u>*/g;
mystr = mystr.replace(re, "");
}
if (mystr.indexOf("<br>") != -1)
{
var ss, t;
var lngest;
ss = mystr.split("<br>");
lngest = ss[0].length;
for (t=0; t < ss.length; t++)
{
if (ss[t].length > lngest)
{
lngest = ss[t].length;
}
}
}
else {
lngest = mystr.length;
}
return(lngest);
}
// -->
</script>
<body bgcolor="gainsboro" onload="startup();">
<table bgcolor="white" border height="480px" width="764px" cellpadding="0" cellspacing="0">
<tr>
<td align="center">
<table nowrap>
<tr>
<td><img width="700px" height="1px" src="./resources/images/w.gif"></td>
<td>
<div class="testclass" id="test"></div>
</td>
</tr>
</table>
</td>
</tr>
</table>
<center>
<form>
<p>
<input type="button" onclick="doBack(); return false" value="Back">
<input type="button" onclick="doNext(); return false" value="Next">
JS:
var _____WB$wombat$assign$function_____ = function(name) {return (self._wb_wombat && self._wb_wombat.local_init && self._wb_wombat.local_init(name)) || self[name]; };
if (!self.__WB_pmw) { self.__WB_pmw = function(obj) { this.__WB_source = obj; return this; } }
{
let window = _____WB$wombat$assign$function_____("window");
let self = _____WB$wombat$assign$function_____("self");
let document = _____WB$wombat$assign$function_____("document");
let location = _____WB$wombat$assign$function_____("location");
let top = _____WB$wombat$assign$function_____("top");
let parent = _____WB$wombat$assign$function_____("parent");
let frames = _____WB$wombat$assign$function_____("frames");
let opener = _____WB$wombat$assign$function_____("opener");
function CaptionArray(len) {
this.length=len
}
Caption = new CaptionArray(499);
Caption[0] = "leaf and the ants as latterly"
Caption[1] = "thought<br>living in<br>Davis would<br>be ok"
Caption[2] = "sure arm today"
Caption[3] = "AMY<br><br>no we<br>both do<br>different<br>songs together"
Caption[4] = "much of anything she doesn't like that at all"
Caption[5] = "SUNG AS LAKE<br><br><br>that never wanted back to come"
Caption[6] = "five sound shut doors"
Caption[7] = "oh<br>my nose is<br>so<br>red<br>Obediah<br>dear"
Caption[8] = "these<br>cubes<br>have been<br>on the floor"
Caption[9] = "sweating importunate"
Caption[10] = "all over noises phone rings"
Caption[11] = "I think this is the water supply for Lake Johnsbury"
Caption[12] = "Paw so greasy"
Caption[13] = "BLACK & WHITE RAIN<br><br><br>clear water grey drops<br><br><br>on windshields in a line<br><br><br>of cars progressing slowly<br><br><br>with windshield wipers wiping"
Caption[14] = "EMILY<br><br>Roger,<br><br>are you<br><br>thinking of me"
Caption[15] = "STICKS<br><br><br>rhythm is inside the sound like another"
Caption[16] = "I think their dog always barks when coming back from the woods"
Caption[17] = "weren't there<br><br>conversations"
Caption[18] = "LOOKING AT FIRE<br><br><u>ashes</u> to ashes<br><br>looking at the fire<br><br>at has been added"
Caption[19] = "a the bank"
}
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 months ago.
Improve this question
*This calculator is only for one digit calculations
In my code there are 3 textboxes Two for values and one for Operators.
I want that if first textbox isn't empty and user clicks on any number than that value should be added in another textbox.
When I click Enter it doesn't display result and I didn't show any kind of error in console
// Textboxes, Enter and Reset
var txt1 = document.querySelector("#txt1");
var txt2 = document.querySelector("#txt2");
var txt3 = document.querySelector("#txt3");
var ent = document.querySelector("#ent");
var res = document.querySelector("#res");
// Number-Buttons
var b1 = document.querySelector("#b1");
var b2 = document.querySelector("#b2");
var b3 = document.querySelector("#b3");
var b4 = document.querySelector("#b4");
var b5 = document.querySelector("#b");
var b6 = document.querySelector("#b6");
var b7 = document.querySelector("#b7");
var b8 = document.querySelector("#b8");
var b9 = document.querySelector("#b9");
// Operators
var add = document.querySelector("#add");
var sub = document.querySelector("#sub");
var mul = document.querySelector("#mul");
var div = document.querySelector("#div");
if (txt1.value == "") {
function B1() { txt1.value = "1" }
function B2() { txt1.value = "2" }
function B3() { txt1.value = "3" }
function B4() { txt1.value = "4" }
function B5() { txt1.value = "5" }
function B6() { txt1.value = "6" }
function B7() { txt1.value = "7" }
function B8() { txt1.value = "8" }
function B9() { txt1.value = "9" }
if (txt2.value == "") {
function Add() { txt2.value = "+" }
function Sub() { txt2.value = "-" }
function Mul() { txt2.value = "*" }
function Div() { txt2.value = "/" }
}
// if (txt1.value != "" && txt3.value == "") {
// function B1() { txt3.value = "1" }
// function B2() { txt3.value = "2" }
// function B3() { txt3.value = "3" }
// function B4() { txt3.value = "4" }
// function B5() { txt3.value = "5" }
// function B6() { txt3.value = "6" }
// function B7() { txt3.value = "7" }
// function B8() { txt3.value = "8" }
// function B9() { txt3.value = "9" }
// }
}
function Ent() {
if (txt1.value == "" || txt2.value == "" || txt3.value == "") {
alert("Pls Enter values and select the operator");
}
function sum() {
if (txt2.value == "+") {
var Sum = Number(txt1.value) + Number(txt3.value);
alert(Sum);
console.log(Sum);
}
}
function sub() {
if (txt2.value == "-") {
var Sub = Number(txt1.value) - Number(txt3.value);
alert(Sub);
console.log(Sub);
}
}
function mul() {
if (txt2.value == "*") {
var Mul = Number(txt1.value) * Number(txt3.value);
alert(Mul);
console.log(Mul);
}
}
function div() {
if (txt2.value == "/") {
var Div = Number(txt1.value) / Number(txt3.value);
alert(Div);
console.log(Div);
}
}
}
I tried to understand what you want to do from the code you shared. In the solution you developed, I made subtractions as the numbers are defined as separate buttons. In this direction, I developed a lean solution. This program is used as follows:
Use the numeric keypad to enter the first number.
Click the action you want to perform (+, -, *, /)
Use the numeric keypad to enter the second number.
Click the CALCULATE button to see the result.
Click the CLEAR button to clear the screen.
var firstNumberText = document.getElementById("txt1");
var secondNumberText = document.getElementById("txt2");
var operatorText = document.getElementById("txt3");
var operationText = document.getElementById("txt4");
var resultText = document.getElementById("txt5");
var addButton = document.getElementById("add");
var subButton = document.getElementById("sub");
var mulButton = document.getElementById("mul");
var divButton = document.getElementById("div");
var enterButton = document.getElementById("enter");
var clearButton = document.getElementById("clear");
let status = true;
let currentFirstNumber = "";
let currentSecondNumber = "";
function updateText(){
firstNumberText.innerText = currentFirstNumber;
secondNumberText.innerText = currentSecondNumber;
}
function changeState(operator) {
operatorText.innerText = operator;
status = !status;
}
addButton.addEventListener("click", function() {
changeState("+");
});
subButton.addEventListener("click", function() {
changeState("-");
});
mulButton.addEventListener("click", function() {
changeState("*");
});
divButton.addEventListener("click", function() {
changeState("/");
});
function numberPressed(pressedButton) {
if(status)
currentFirstNumber += pressedButton.value;
else
currentSecondNumber += pressedButton.value;
}
function updateResult(result, operator) {
operationText.innerText = firstNumberText.textContent + operator + secondNumberText.textContent + "=" + `${result}`;
resultText.innerText = result;
}
function calculate() {
if (firstNumberText.value == "" || secondNumberText.value == "" || operatorText.value == "") {
alert("Warning");
return;
}
var result = 0;
if(operatorText.textContent == "+") {
result = parseInt(firstNumberText.textContent) + parseInt(secondNumberText.textContent);
updateResult(result, "+");
}
else if(operatorText.textContent == "-") {
result = parseInt(firstNumberText.textContent) - parseInt(secondNumberText.textContent);
updateResult(result, "-");
}
else if(operatorText.textContent == "*") {
result = parseInt(firstNumberText.textContent) * parseInt(secondNumberText.textContent);
updateResult(result, "*");
}
else if(operatorText.textContent == "/") {
result = parseInt(firstNumberText.textContent) / parseInt(secondNumberText.textContent);
updateResult(result, "/");
}
}
enterButton.addEventListener("click", function() {
calculate();
});
clearButton.addEventListener("click", function() {
status = true;
currentFirstNumber = "";
currentSecondNumber = "";
firstNumberText.innerText = "";
secondNumberText.innerText = "";
operatorText.innerText = "";
operationText.innerText = "";
resultText.innerText = "";
});
<!-- First Number -->
<label id="txt1">-</label><br>
<!-- Operator -->
<label id="txt3">-</label><br>
<!-- Second Number -->
<label id="txt2">-</label><br>
<!-- Operation -->
<label id="txt4">-</label><br>
<!-- Result -->
<label id="txt5">-</label><br>
<button type="button" value="0" onclick='numberPressed(this);updateText()'>0</button>
<button type="button" value="1" onclick='numberPressed(this);updateText()'>1</button>
<button type="button" value="2" onclick='numberPressed(this);updateText()'>2</button>
<button type="button" value="3" onclick='numberPressed(this);updateText()'>3</button>
<button type="button" value="4" onclick='numberPressed(this);updateText()'>4</button>
<button type="button" value="5" onclick='numberPressed(this);updateText()'>5</button>
<button type="button" value="6" onclick='numberPressed(this);updateText()'>6</button>
<button type="button" value="7" onclick='numberPressed(this);updateText()'>7</button>
<button type="button" value="8" onclick='numberPressed(this);updateText()'>8</button>
<button type="button" value="9" onclick='numberPressed(this);updateText()'>9</button>
<br><br>
<button type="button" id="add">+</button>
<button type="button" id="sub">-</button>
<button type="button" id="mul">*</button>
<button type="button" id="div">/</button><br><br>
<button type="button" id="enter">CALCULATE</button>
<button type="button" id="clear">CLEAR</button>
My goal for this experiment is to have 2 blocks of trials, both which flash 10 words and then the participants have to click yes or no if they saw the word or not (answer yes or no to 20 words). After the 2 blocks I would like the data to be displayed and the experiment to end, although right now the experiment is infinite and displays data after every block. I also need to know how to save the data with a "Save Data" button after presenting both of the blocks data at the end. Any and all help appreciated!
If anyone has any ideas about how to create two blocks, as I have tried to initiate by declaring blocks = 0 at the beginning it would be greatly appreciated!
<!DOCTYPE HTML>
<html>
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
<script src="342.js" type="text/javascript"></script>
<script type="text/javascript">
let index = 0, blocks=0;
let words = ["fox", "tree", "wheel", "pillow", "target", "wool", "bread", "sport", "dog", "straw", "state",
"mountain", "cot" , "green" , "napkin" , "grape" , "glass" , "drum" , "grass",];
let stimuli = [];
let N = words.length/2;
let t;
window.onload = initialize;
function initialize() {
for (let i = 0; i < words.length; i++) {
stimuli.push(new Stimulus(words[i]));
}
shuffle(stimuli);
for (let i = 0; i < words.length; i++) {
if (i < N) {
stimuli[i].presented = "1";
stimuli[i].presOrder = i;
}
else {
stimuli[i].presented = "0";
stimuli[i].presOrder = "-1"
}
}
}
function Stimulus(word) {
this.word = word;
}
Stimulus.prototype.toString = function () {
return "\t Order Presented: " + this.presOrder + "\t Order tested: " + this.testOrder + "\t Word Presented:" + this.word + "\t Response (0 or 1):"
+ this.resp + " \t Presented (0 or 1):" + this.presented;
};
function begin() {
document.getElementById("b").style.visibility = "hidden";
document.getElementById("word").innerHTML = "";
t = setInterval(nextWord, 250)
}
function nextWordTest() {
document.getElementById("word").innerHTML = stimuli[index].word;
stimuli[index].testOrder = index;
if (blocks=1)
{
document.getElementById("b2").style.visibility = "visible";
}
}
function nextWord()
{
if (index < N)
{
document.getElementById("word").innerHTML = stimuli[index].word;
stimuli[index].presOrder = index;
index++;
}
else
{
clearInterval(t);
document.getElementById("word").innerHTML = "Click yes if you saw the word and " +
"no if you did not see the word";
document.getElementById("yes").style.visibility = "visible";
document.getElementById("no").style.visibility = "visible";
document.getElementById("b2").style.visibility = "hidden";
index = 0;
N = words.length;
stimuli = shuffle(stimuli);
nextWordTest();
}
}
function record(resp) {
stimuli[index].resp = resp;
index++;
if (index < N) {
nextWordTest();
}
else {
if (blocks===0){
nextWordTest()
}
if (blocks===1)
{
document.getElementById("word").innerHTML = "finished";
data = "";
for (let i = 0; i < stimuli.length; i++)
{
data += stimuli[i] + "\n";
}
console.log(data);
document.getElementById("word").innerText = data;
}
}
}
</script>
</head>
<body>
<h1> Attentional Blink Experiment </h1>
<p id="word">Push button to begin.</p>
<button type="button" id="yes" onclick="record(1)" style="visibility: hidden">yes</button>
<button type="button" id="no" onclick="record(0)" style="visibility: hidden">no</button>
<button type="button" id="b" onclick="begin()">Begin</button>
<button type="button" id="b2" onclick="begin()" style="visibility: hidden">Continue</button>
</body>
</html>
When a user inputs a sentence into the title box they are supposed to be able to generate 72 different variations of that title with words being replaced and words changing positions. The problem that is occurring is that it will not take the user input and do anything with it. It works if you pre-define the text within the array.
Below is the html used.
<html>
<head>
<title> Title Generation Module</title>
<script src="title.js" type="text/javascript"></script>
<script src="find.js" type="text/javascript"></script>
<script src="replace.js" type="text/javascript"></script>
<script src="search.js" type="text/javascript"></script>
<script src="generate.js" type="text/javascript"></script>
<!-- <script src="check.js" type="text/javascript"></script>--> <!-- Leaving for future usage not needed at this point -->
<link rel="stylesheet" type="text/css" href="title.css">
</head>
<body>
<h1>Title Generation Module</h1>
<div id="cWords">
<h3>Words That Might Return an Invalid Title</h3>
<ul>
<li>For</li>
<li>You</li>
<li>Two</li>
<li>With</li>
<li>Adaptor</li>
<li>Wireless</li>
</ul>
</div>
<!-- This allows the user to input a title -->
<h3>Input Title into Text Field</h3>
<input type="text" id="title" style="height:20px; width: 500px;">
<p>Click the Submit button. To see if the title is a good working title click on the check title button below.</p>
<button onclick="getTitle()">Submit</button>
<p id="displayTitle" class="title"></p>
<!-- This allows the user to hightllight a keyword in the Title -->
<p>Find Keywords in your sentence</p>
<input id="kText">
<button onclick="getSearch()">Search</button>
<!-- This allows the user to change the keyword within a title to a new word -->
<p>Changes You Want to Make to Keywords</p>
<input type="text" id="change">
<button onclick="newTitle()">Change Keyword</button>
<!-- Button Reloads the page -->
<button onclick="myFunction()">Reload page</button>
<!-- Reloads the page -->
<script>
function myFunction()
{
location.reload();
}
</script>
<!-- Change the Order of the Title -->
<button onclick="generate_title()">Generate Title</button>
<button onclick="displayTitle()">Display Title</button>
<script>
function displayTitle()
{
var dpTitle = document.getElementById("displayTitle").innerHTML;
alert(dpTitle);
}
</script>
</body>
</html>
Below is the javascript that will handle the function of replacing and displaying the user input.
var keyword = document.getElementById("displayTitle").innerHTML;
var kText = document.getElementById("kText").value;
var changeWord = document.getElementById("change").value;
var newKeyword = new Array(keyword);
newKeyword = keyword.split(kText).join(changeWord);
var input_keywords =
[
[check],
//[checkY,checkY],
["Cordless-","Wireless"],
["Rechargeable+"],
["you"]
].filter(function(item){
return item.length <= 80;
});
/*[
["Men", "Women", "Unisex"],
["1", "2", "3", "fourrrrrrrrrr"],
["Candy Color"],
["Spring"],
["Ski+"],
["Crochet"],
["Hip-hop"],
["Hat Beanie-"],
["One Size+"]].filter(function(item)
{
return item.length <= 80;
});
*/
/*
var input_keywords = [
["Women Men", "Men Women", "Unisex Women Men", "Unisex Men Women", "Unisex", "Womens Mens", "Mens Womens", "Unisex Womens Mens", "Unisex Mens Womens"],
["Fashion", "Trendy", "Stylish", "Korea Style"],
["Candy Color"],
["Spring", "Summer", "Winter"],
["Ski"],
["Crochet", "Knit", "Knitted"],
["Elastic", "Strechable"],
["Hip-hop", "Dance"],
["Hat", "Cap", "Beanie", "Hat Cap", "Hat Beanie", "Hat Cap Beanie"],
["One Size"]
].filter(function(item){
return item.length <= 80;
});
*/
var limit_count = 1;
var max_char_per_title = 80;
var sub_library = ["for=4", "you=u", "at=#", "two=2", "with=w", "adapter=adpt", "Monokini=Mono 9"].map( function (item)
{ return item.split("=");});
function calc_length(title)
{
return (title
.join(" ") + " ")
.replace("- ", " ")
.replace("+ ", " ")
.replace("* ", " ")
.replace(" ", " ")
.replace("\" ", " ")
.replace(" \"", " ")
.length - 1;
}
function get_all_titles(keywords)
{
var result_titles = [];
for(var i = 0; i < keywords.length; i ++)
{
var word_count = keywords[i].length;
var words = keywords[i];
var previous_count = result_titles.length;
if (previous_count == 0)
{
previous_count = word_count;
for (var sub_ii = 0 ; sub_ii < word_count; sub_ii++)
{
result_titles[sub_ii] = [];
result_titles[sub_ii][i] = words[sub_ii];
}
}
else
{
for (var sub_i = 0; sub_i < word_count; sub_i++)
{
for (var sub_ii = 0 ; sub_ii < previous_count; sub_ii++)
{
if (result_titles[previous_count * sub_i + sub_ii] == undefined)
{
result_titles[previous_count * sub_i + sub_ii] = result_titles[sub_ii ].slice();
}
result_titles[previous_count * sub_i + sub_ii][i] = words[sub_i];
}
}
}
}
return result_titles;
}
function substitute(title)
{
for (var subs_idx = 0 ; subs_idx < sub_library.length; subs_idx++)
{
var index = title.indexOf(sub_library[subs_idx][0]);
if (index >= 0)
{
title[index] = sub_library[subs_idx][1];
}
}
return title;
}
function shorten_title_length(titles)
{
var result = [];
var count = 0;
for (var i = 0 ; i < titles.length; i++)
{
if (calc_length(titles[i]) > max_char_per_title)
{
//substitute with the word in library
titles[i] = substitute(titles[i]);
// still too long, remove possible words.
if (calc_length(titles[i]) > max_char_per_title)
{
var words = titles[i];
for (var word_idx = 0 ; word_idx < words.length; word_idx++)
{
if (words[word_idx].indexOf("/") == (words[word_idx].length - 1))
{
titles[i] = titles[i].splice(word_idx, 1);
}
}
titles[i] = words
}
}
if (calc_length(titles[i]) <= max_char_per_title)
{
result[count] = titles[i];
count++;
}
else
{
console.log(titles[i].join(" \ "));
}
}
return result;
}
function change_forward_position(title)
{
var words = title;
for (var word_idx = 0 ; word_idx < words.length; word_idx++)
{
if (words[word_idx][words[word_idx].length - 1] == "-")
{
if (word_idx != words.length - 1)
{
var tmp = words[word_idx];
words[word_idx] = words[word_idx + 1];
words[word_idx + 1] = tmp;
word_idx ++;
}
}
}
title = words;
return title;
}
function change_backward_position(title)
{
var words = title;
for (var word_idx = 0 ; word_idx < words.length; word_idx++)
{
if (words[word_idx][words[word_idx].length - 1] == "+")
{
if (word_idx != 0)
{
var tmp = words[word_idx];
words[word_idx] = words[word_idx - 1];
words[word_idx - 1] = tmp;
}
}
}
title = words;
return title;
}
function finalize(titles)
{
for (var title_idx = 0 ; title_idx < titles.length; title_idx++)
{
for (var word_idx = 0 ; word_idx < titles[title_idx].length; word_idx++)
{
if (titles[title_idx][word_idx][titles[title_idx][word_idx].length - 1] == '+')
titles[title_idx][word_idx] = titles[title_idx][word_idx].substring(0, titles[title_idx][word_idx].length - 1);
if (titles[title_idx][word_idx][titles[title_idx][word_idx].length - 1] == '-')
titles[title_idx][word_idx] = titles[title_idx][word_idx].substring(0, titles[title_idx][word_idx].length - 1);
if (titles[title_idx][word_idx][titles[title_idx][word_idx].length - 1] == '/')
titles[title_idx][word_idx] = titles[title_idx][word_idx].substring(0, titles[title_idx][word_idx].length - 1);
if (titles[title_idx][word_idx][titles[title_idx][word_idx].length - 1] == '"')
titles[title_idx][word_idx] = titles[title_idx][word_idx].substring(0, titles[title_idx][word_idx].length - 1);
if (titles[title_idx][word_idx][titles[title_idx][word_idx].length - 1] == '*')
titles[title_idx][word_idx] = titles[title_idx][word_idx].substring(0, titles[title_idx][word_idx].length - 1);
}
}
return titles;
}
function generate_title()
{
var all_titles = get_all_titles(newKeyword);
//Check keyword files provided by the user, that optional sub words are at least 24
if (all_titles.length < limit_count)
{
alert("not enough different titles");
}
//check total char per title
all_titles = shorten_title_length(all_titles);
// substitute half randomly.
for (var i = 0 ; i < all_titles.length; i++)
{
if (Math.random() > 0.5)
{
all_titles[i] = substitute(all_titles[i]);
}
}
//changing position backward.
for (var i = 0 ; i < all_titles.length; i++)
{
if (Math.random() > 0.5)
{
all_titles[i] = change_backward_position(all_titles[i]);
}
}
//changing position forward.
for (var i = 0 ; i < all_titles.length; i++)
{
if (Math.random() > 0.5)
{
all_titles[i] = change_forward_position(all_titles[i]);
}
}
all_titles = finalize(all_titles);
// evaluate.....
for (var i = 0 ; i < all_titles.length; i++)
{
console.log(i);
console.log(all_titles[i].join(" \ "));
console.log(all_titles[i].length);
alert(all_titles);
}
}
Open modal window after form calculations function is complete
I have a basic form that has check boxes. Each checkbox is a different (simple) calculation. At the end of the function some more calculations are done and stored in variables.
I need to first run this calculation function from an onclick event and then display them in a modal window.
I am using Magnific-Pop up at the moment.
I know that the calculations have to be done first so the variables have the data. But I don’t know how to run the function and then pop up the window.
Now, when the button is clicked the window opens before the function is run.
Form button
<input type="submit" class="calculate ajax-popup-link" href="dev/calculator/results1.html" value="Calculate Savings" onclick=”calculate();”>
The Modal window
$('.ajax-popup-link').magnificPopup({
items: {
src: '#popup',
type: 'inline',
//preloader: true,
},
});
This code displays a div with all the variables. The constant variables display but not the final calcs.
Here is the div
<div id="popup" class="white-popup mfp-hide">
<table class="data savings">
<thead>
<tr>
<th colspan="2"><script>document.write(VarFromCalc);</script></th>
</tr>
</thead>
<tbody>
<tr>
<td>Number of patients with potential Reduced Length of Stay</td>
<td class="stay" id="stay">$ <script>document.write(totalN);
</script> </td>
</tr>
</tbody>
</table>
If the modal window (of course) opens before the calculations are done the values are 0.
I hope this makes sense. If you need more info let me know.
Here is the calculation script.
<script>
var n3, n4, n5, n6, totalW, totalB, totalU, totalT, totalN;
var finalCalc;
var n7;
function calculate() {
if (document.getElementById('check1').checked) {
var check01 = 6 * 7.08;
var c01 = check01.toFixed(2);
}
else {var c01 = 0;}
if (document.getElementById('check2').checked) {
var check02 = 4 * 4.62;
var c02 = check02.toFixed(2);
}
else {var c02 = 0;}
if (document.getElementById('check3').checked) {
var check03 = 6 * 13.20;
var c03 = check03.toFixed(2);
}
else {var c03 = 0;}
if (document.getElementById('check4').checked) {
var check04 = 6 * 16.00;
var c04 = check04.toFixed(2);
}
else {var c04 = 0;}
if (document.getElementById('check5').checked) {
var check05 = 3 * 1.32;
var c05 = check05.toFixed(2);
}
else {var c05 = 0;}
if (document.getElementById('check6').checked) {
var check06 = 1 * 12.30;
var c06 = check06.toFixed(2);
}
else {var c06 = 0;}
if (document.getElementById('check7').checked) {
var check07 = 4 * 3.16;
var c07 = check07.toFixed(2);
}
else {var c07 = 0;}
if (document.getElementById('check8').checked) {
var check08 = 4 * 4.68;
var c08 = check08.toFixed(2);
}
else {var c08 = 0;}
if (document.getElementById('check9').checked) {
var check09 = 3 * 12.91;
var c09 = check09.toFixed(2);
}
else {var c09 = 0;}
if (document.getElementById('check10').checked) {
var check10 = 3 * 13.55;
var c10 = check10.toFixed(2);
}
else {var c10 = 0;}
if (document.getElementById('check11').checked) {
var check11 = 3 * 50.60;
var c11 = check11.toFixed(2);
}
else {var c11 = 0;}
if (document.getElementById('check12').checked) {
var check12 = 4 * 11.36;
var c12 = check12.toFixed(2);
}
else {var c12 = 0;}
if (document.getElementById('check13').checked) {
var check13 = 1 * 93.58;
var c13 = check13.toFixed(2);
}
else {var c13 = 0;}
if (document.getElementById('check14').checked) {
var check14 = 3 * 18.48;
var c14 = check14.toFixed(2);
}
else {var c14 = 0;}
if (document.getElementById('check15').checked) {
var check15 = 3 * 39.93;
var c15 = check15.toFixed(2);
}
else {var c15 = 0;}
if (document.getElementById('check16').checked) {
var check16 = 2 * 5.98;
var c16 = check16.toFixed(2);
}
else {var c16 = 0;}
if (document.getElementById('check17').checked) {
var check17 = 1 * 12.30;
var c17 = check17.toFixed(2);
}
else {var c17 = 0;}
if (document.getElementById('check18').checked) {
var check18 = 1 * 50.73;
var c18 = check18.toFixed(2);
}
else {var c18 = 0;}
if (document.getElementById('check19').checked) {
var check19 = 3 * 4.36;
var c19 = check19.toFixed(2);
}
else {var c19 = 0;}
if (document.getElementById('check20').checked) {
var check20 = 3 * 284.58;
var c20 = check20.toFixed(2);
}
else {var c20 = 0;}
if (document.getElementById('check21').checked) {
var check21 = 1 * 214.27;
var c21 = check21.toFixed(2);
}
else {var c21 = 0;}
if (document.getElementById('check22').checked) {
var check22 = 2 * 78.00;
var c22 = check22.toFixed(2);
}
else {var c22 = 0;}
if (document.getElementById('check23').checked) {
var check23 = 4 * 6.13;
var c23 = check23.toFixed(2);
}
else {var c23 = 0;}
if (document.getElementById('check24').checked) {
var check24 = 1 * 4.78;
var c24 = check24.toFixed(2);
}
else {var c24 = 0;}
if (document.getElementById('check25').checked) {
var check25 = 2 * 14.52;
var c25 = check25.toFixed(2);
}
else {var c25 = 0;}
if (document.getElementById('check26').checked) {
var check26 = 1 * 229.44;
var c26 = check26.toFixed(2);
}
else {var c26 = 0;}
if (document.getElementById('check27').checked) {
var check27 = 1 * 9.68;
var c27 = check27.toFixed(2);
}
else {var c27 = 0;}
var h51 = (parseFloat(c01) + parseFloat(c02) + parseFloat(c03) + parseFloat(c04) + parseFloat(c05) + parseFloat(c06) + parseFloat(c07) + parseFloat(c08) + parseFloat(c09) + parseFloat(c10) + parseFloat(c11) + parseFloat(c12) + parseFloat(c13) + parseFloat(c14) + parseFloat(c15) + parseFloat(c16) + parseFloat(c17) + parseFloat(c18) + parseFloat(c19) + parseFloat(c20) + parseFloat(c21) + parseFloat(c22) + parseFloat(c23) + parseFloat(c24) + parseFloat(c25) + parseFloat(c26) + parseFloat(c27));
//per month calcs
var j3 = parseFloat(100);
var j4 = parseFloat(200);
var j5 = parseFloat(250);
var j6 = parseFloat(200);
var j7 = parseFloat(600);
var k3 = parseFloat(j3) * 12;
var k4 = parseFloat(j4) * 12;
var k5 = parseFloat(j5) * 12;
var k6 = parseFloat(j6) * 12;
//var k7 = parseFloat(j7)*12;
var l3 = parseFloat(3573);
var l4 = parseFloat(2033);
var l5 = parseFloat(4706);
var l6 = parseFloat(3437);
var m3 = parseFloat(j3)*parseInt(l3);
var m4 = parseFloat(j4)*parseInt(l4);
var m5 = parseFloat(j5)*parseInt(l5);
var m6 = parseFloat(j6)*parseInt(l6);
n3 = Math.round(parseFloat(k3)*parseFloat(l3));
n4 = Math.round(parseFloat(k4)*parseFloat(l4));
n5 = Math.round(parseFloat(k5)*parseFloat(l5));
n6 = Math.round(parseFloat(m6) * 12);
n7 = Math.round(parseFloat(j7) * parseFloat(h51) * 12);
//STORE FINAL CALCS
totalW = n3.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
totalB = n4.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
totalU = n5.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
totalT = n6.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
totalN = n7.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
var totalCalc = Math.round(parseFloat(n3) + parseFloat(n4) + parseFloat(n5) + parseFloat(n6) + parseFloat(n7));
finalCalc = totalCalc.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
$('.ajax-popup-link').click();
}
</script>
Then i try to show the vars in the hidden div popup as such
<tr>
<td>Total ID/AST Cultures</td>
<td class="cultures" id="cultures">$ <script>document.write(totalT);</script></td>
</tr>
Google Charts Code
var data = google.visualization.arrayToDataTable([
['Element', 'Savings', { role: 'style' }],
['Reduced Length of Stay', n7, ''],
['Total ID/AST Cultures', n6, ''],
['Urine', n5, ''],
['Blood', n4, ''],
['Wound/Abscess', n3, '' ],
]);
I don't know much about magnificPopup, but in this case, you can actually just add a hidden div with "ajax-popup-link" class, and remove this class from the link.
in the Calculate() function, after everything is done, you call "$('.ajax-popup-link').click()" to bring up the modal.
To implement it, do like following:
change
<input type="submit" class="calculate ajax-popup-link" href="dev/calculator/results1.html" value="Calculate Savings" onclick=”calculate();”>
to
<input type="button" class="calculate" href="dev/calculator/results1.html" value="Calculate Savings" onclick=”calculate();”>
To correctly set the calculated value to the popup window, you can add a id to the node that need to display the value, like following html code:
<th colspan="2" id="var_from_calc"></th>
And in the calculate() function, after you have finished calculating, add this code:
$('#var_from_calc').html(VarFromCalc);
$('#stay').html(totalN);
$('.ajax-popup-link').click()
Here is a snippet/html of my work.
<script language="javascript">
var imagesArray = [
'images/img-1.jpg',
'images/img-2.jpg',
'images/img-3.jpg',
'images/img-4.jpg',
'images/img-5.jpg',
'images/img-6.jpg',
'images/img-7.jpg'
];
var usedImages = {};
var usedImagesCount = 0;
var score = 0;
function displayImage(){
var num = Math.floor(Math.random() * (imagesArray.length));
if (!usedImages[num]){
document.canvas.src = imagesArray[num];
usedImages[num] = true;
usedImagesCount++;
if (usedImagesCount === imagesArray.length){
usedImagesCount = 0;
usedImages = {};
}
} else {
displayImage();
}
}
function check(){
x = prompt('What is the movie title?');
var y;
if (document.canvas.src=='images/img-1.jpg'){
y = 'The Expandables';}
if (document.canvas.src=='images/img-2.jpg'){
y = 'License to Wed';}
if (document.canvas.src=='images/img-3.jpg'){
y = "Schindler's List";}
if (document.canvas.src=='images/img-4.jpg'){
y = 'The Heartbreak Kid';}
if (document.canvas.src=='images/img-5.jpg'){
y = 'The Interview';}
if (document.canvas.src=='images/img-6.jpg'){
y = 'How To Train Your Dragon 2';}
if (document.canvas.src=='images/img-7.jpg'){
y = 'Avatar';}
if (y == x){
score = score + 10;
alert('Your points is ', score ,'.');}
else{
score = score;
alert('Your points is ', score ,'.')}
var num = Math.floor(Math.random() * (imagesArray.length));
if (!usedImages[num]){
document.canvas.src = imagesArray[num];
usedImages[num] = true;
usedImagesCount++;
if (usedImagesCount === imagesArray.length){
usedImagesCount = 0;
usedImages = {};
}
} else {
displayImage();
}
}
</script>
<html>
<body>
<form name="imageForm">
<table border=3>
<tr align="center">
<td>
<input onclick="displayImage();" type=button value="Start!">
</td>
</tr>
<tr>
<td>
<img src="blank.jpg" name="canvas" />
</td>
</tr>
</table>
<input onclick="check();" type=button value="Answer!">
</form>
</body>
</html>
When I run the JScript:
The output is OK except that the JScript alert is:
Your points is
regardless if my answer was right or wrong.
Why doesn't it display the score? What was my mistake?
You can concatenate strings using +, not using ,:
alert('Your score is ' + score + '.');