Automate checking process - javascript

The code below returns me 'even' or 'odd', but I have to always change, what to do for him to check 25 to 115 and show result in the body of the page?
<html>
<title>FrontPage</title>
</head>
<body>
<form method="post" name="Form1" onsubmit="Check();">
<input type="submit" value="Submit" name="bSubmit"></p>
</form>
<script type="text/javascript">
function Check() {
var n = "26";
var finish = n/2;
if(n & 1){
alert("Impar");
} else {
alert("Par");
}
alert(finish);
}
</script>
</body>
</html>

var btn = document.querySelector('#btn');
var result = document.querySelector('#result');
btn.addEventListener('click', function() {
for (var i = 25; i <= 115; i++) {
var li = document.createElement('li');
li.innerText = i.toString() + ' - ' + ((i & 1) ? 'Impar' : 'Par');
result.append(li);
}
});
<input id="btn" type="submit" value="Submit" name="bSubmit">
<ul id="result"></ul>

Just implement your code within a for-loop (since you know exactly how many iterations you need):
document.querySelector('#btnSubmit').addEventListener('click', function(e) {
var min = 25;
var max = 115;
var i;
for (i = min; i <= max; i += 1) {
console.log(check(i));
}
});
function check(n) {
var s = `${n} is `;
s += n % 2 === 0 ? "even" : "odd";
return s;
}
check();
<input id="btnSubmit" type="button" value="Check" />

You need to use the foor loop like so:
const append = str => document.getElementById('print').innerHTML += str;
document.getElementById('btn').addEventListener('click', function () {
for (let i = 25; i <= 115; i++) {
const result = i % 2 === 0 ? 'even' : 'odd';
append(`<p>Number ${i} is ${result}</p>`);
}
});
<button id="btn">Result</button>
<div id="print"></div>

Related

Javascript for card shuffle failing

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"
}

Loop through the sum of the two inputs until in doubled (javascript)

I am stuck here with duch issue. There are 2 two entry boxes are for an amount and an interest rate (%).
If you click on the button, the page will show an overview of the balance until the amount have to be doubled.
Taking a simple numbers forexample 10 - is amount and 4 - is 4% intereste rate. So the result have to stop on amount of 20.
document.getElementById("button").onclick = loop;
var inputB = document.getElementById("inputB");
var inputC = document.getElementById("inputC");
var result = document.getElementById("result")
function loop() {
var s = inputB.value;
var r = inputC.value;
var doubleS = s * 2;
for (var i = 1; i <= doubleS; i++) {
s = ((r / 100 + 1) * s);
result.innerHTML += s + "<br>";
}
}
<! DOCTYPE html>
<html>
<body>
<br>
<input type="text" id="inputB" value="10"><br>
<input type="text" id="inputC" value="4"><br><br>
<button id="button">Klik</button>
<p> De ingevoerde resultaten: </p>
<p id="result"></p>
<script async src="oefin1.js"></script>
</body>
</html>
The issue is with your for loop bounds.
This will loop doubleX number of times: for (var i = 0; i < doubleX; i++)
This will loop until x surpasses doubleX: for (;x < doubleX;), which btw is better written with a while loop: while (x < doubleX)
document.getElementById("button").onclick = loop;
var inputB = document.getElementById("inputB");
var inputC = document.getElementById("inputC");
var result = document.getElementById("result")
function loop() {
var s = inputB.value;
var r = inputC.value;
var doubleS = s * 2;
result.innerHTML = '';
while (s < doubleS) {
s = ((r / 100 + 1) * s);
result.innerHTML += s + "<br>";
}
}
<input type="text" id="inputB" value="10"><br>
<input type="text" id="inputC" value="4"><br><br>
<button id="button">Klik</button>
<p> De ingevoerde resultaten: </p>
<p id="result"></p>
Easiest way is to just use a for loop without the convoluted math with s in the middle:
function loop() {
var s = inputB.value;
var r = inputC.value;
var doubleS = s * 2;
for (var i = s; i <= doubleS; i *= ((r / 100) + 1)) {
result.innerHTML += i + "<br>";
}
}
use a while loop and check is the value of s is bigger than or equal to doubleS
document.getElementById("button").onclick = loop;
var inputB = document.getElementById("inputB");
var inputC = document.getElementById("inputC");
var result = document.getElementById("result")
function loop() {
var s = inputB.value;
var r = inputC.value;
var doubleS = s * 2;
while(true) {
s = ((r / 100 + 1) * s);
result.innerHTML += s + "<br>";
if(s >= doubleS){
break
}
}
}
<! DOCTYPE html>
<html>
<body>
<br>
<input type="text" id="inputB" value="10"><br>
<input type="text" id="inputC" value="4"><br><br>
<button id="button">Klik</button>
<p> De ingevoerde resultaten: </p>
<p id="result"></p>
<script async src="oefin1.js"></script>
</body>
</html>

How to make 1 block javascript experiment into 2 blocks that presents data at the end of the 2nd block and then save data to a local sever using MAMP

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>

How to make Ulam number sequence in javascript?

I can't figure this problem out, I already checked my code but I don't know what the problem is.
This is the question: A mathematician Ulam proposed generating a sequence of numbers from any positive integer n (n>0) as follows.
if n is 1, it will stop.
if n is even, the next number is n/2.
if n is odd, the next number is 3 * n + 1.
continue with the process until reaching 1.
here some examples for the first few integers.
2->1
3->10->5->16->8->4->2->1
4->2->1
6->3->10->5->16->8->4->2->1
7->22->11->34->17->52->26->13->40->20->10->5->16->8->4->2->1
Sample Run:
Enter Positive Integer: 5
The ulam Number Sequence is : 5->16->8->4->2->1
this is my code...
<!DOCTYPE html>
<html>
<head>
<title>Ulam Number Sequence</title>
</head>
<body>
<form name="myform" onsubmit=" return false">
Enter positive integer: <input type="number" id="num" required>
<button onclick="process()">Process</button>
<button onclick="Reset()">Reset</button>
</form>
<p id = "info"> </p>
<script>
function isOdd(num) {
var odd = true;
for (var i = 0; i <= num; i++) {
if (num % i == 0) {
odd = false;
break;
}
}
return odd;
}
function isEven(num) {
var even = true;
for (var i = 0; i <= num; i++) {
if (num % i == 1) {
even = false;
break;
}
}
return even;
}
function process(){
var n = parseInt(document.getElementById("num").value);
var result1 = [];
for(var i = 0; i <= n; i++){
if(isOdd(i)){
result1[result1.length] = i /2;
}
if(isEven(i)){
result1[result1.length] = 3 * i + 1;
}
if(isOdd(result1)){
result1[result1.length] = result1 / 2;
}
if(isEven(result1)){
result1[result1.length] = 3 * result1 +1;
}
//result1[result1.length] = i * 3 + 1;
document.getElementById("info").innerHTML = result1.join("->");
}
}
function Reset(){
document.getElementById("info").innerHTML = "";
document.getElementById("num").value = "" ;
}
</script>
</body>
</html>
Maybe this is a solution for you (and a little hint):
function process() {
var n = parseInt(document.getElementById('num').value),
result = [n];
if (isFinite(n) && n && n === Math.abs(n)) {
while (n !== 1) {
// basically this is all to do.
n = n % 2 ? 3 * n + 1 : n / 2;
result.push(n);
}
document.getElementById("info").innerHTML = result.join(' > ');
} else {
document.getElementById("info").innerHTML = 'Does not compute!';
}
}
function reset() {
document.getElementById('info').innerHTML = '';
document.getElementById('num').value = ''
}
<form name="myform" onsubmit=" return false">
Enter positive integer: <input type="number" id="num" required>
<button onclick="process()">Process</button>
<button onclick="reset()">Reset</button>
</form>
<p id="info"></p>

How can I show a dollar sign before the amount value when the checkbox is checked?

When the checkbox is not checked it will show $0.00.
When I check the checkbox, it will show 1.00. I want it to show $1.00. How can I do that?
Demo on JS Fiddle
This is the code:
<form id="form1" method="post">
<input type="text" id="totalcost" value="$0.00">
<input type="checkbox" value="aa_1">
<input type="checkbox" value="aa_2">
<input type="checkbox" value="aa_3">
</form>
<script type="text/javascript">
var clickHandlers = (function () {
var form1 = document.getElementById("form1"),
totalcost = document.getElementById("totalcost"),
// if this is always the last input in the form, we could avoid hitting document again with
// totalcost = form1[form1.length - 1];
sum = 0;
form1.onclick = function (e) {
e = e || window.event;
var thisInput = e.target || e.srcElement;
if (thisInput.nodeName.toLowerCase() === 'input') {
if (thisInput.checked) {
var val = thisInput.value, // "bgh_9.99"
split_array = val.split("_"), // ["bgh", "9.99"]
pay_out_value = split_array[1]; // "9.99"
sum += parseFloat(pay_out_value); // 9.99
} else {
if (thisInput.type.toLowerCase() === 'checkbox') {
var val = thisInput.value, // "bgh_9.99"
split_array = val.split("_"), // ["bgh", "9.99"]
pay_out_value = split_array[1]; // "9.99"
sum -= parseFloat(pay_out_value); // 9.99
}
}
totalcost.value = (sum > 0) ? sum.toFixed(2) : "$0.00";
}
}
return null;
}());
</script>
Simply change this line:
totalcost.value = (sum > 0) ? sum.toFixed(2) : "$0.00";
to
totalcost.value = (sum > 0) ? "$" + sum.toFixed(2) : "$0.00";
^
This will add $ before your price !
FIDDLE
Just append the $ to the value:
totalcost.value = (sum > 0) ? '$' + sum.toFixed(2) : "$0.00";
Fiddle

Categories