<p> Shows only last value assigned - javascript

I have a code, in which I try to achieve needed string("Hey!") by randomizing characters (brute-forcing the string), and to display all steps in a <p>(next step overwrites previous one). The problem is, however, that in the #first, there is only displayed the final step of permutations ("Hey!").
Why doesn't it displays all steps one after one, only the last one? I will appreciate any help on that problem.
Note: in the console, all steps are logged. I also tried outputting string in <p> with timeout; nothing changed.
Example of what has to be: https://i.imgur.com/fNjhjUS.gif
Here's my Javascript code and HTML:
var fline = ["H", "e", "y", "!"];
temp_fline = [" ", " ", " ", " "],
index = 0,
possible = "!abc!defghijklmnopqrstuvwxyz!ABCDEFGHIJKLMNOPQRSTUVWXYZ!";
while (index < 4)
{
if (fline[index] != temp_fline[index])
temp_fline[index] = possible[Math.round(Math.random() * 57)];
if (fline[index] == temp_fline[index])
++index;
var tempString = "";
for (var i = 0; i < 4; ++i)
tempString += temp_fline[i];
console.log(tempString);
document.getElementById("fline").innerHTML = '> ' + tempString;
}
<html>
<body>
<div id="first">
<br>
<p id="fline"></p>
<br><br><br>
<p id="sline"></p>
<br><br><br>
<p id="tline"></p>
<br><br><br>
<p id="fhline"></p>
</div>
</body>
</html>

Want like that?
var fline = ["L", "i", "k", "e", " ", "t", "h", "i", "s", "?"], count = 0, index = 0, flist = [],
possible = "!abc!?defghijklmnopqrstuvwxyz!ABCDEFGHIJKLMNOPQRSTUVWXYZ! ";
let found = document.getElementById("found");
let checking = document.getElementById("checking");
let timer = setInterval(function ()
{
if (index >= fline.length)
{
console.log(flist);
clearInterval(timer);
checking.innerText = "";
flist = [];
}
else
{
if (fline[index] == possible[count])
{
found.innerText += possible[count];
flist.push(possible[count]);
index++; count = 0;
}
else
{
checking.innerText = possible[count];
count++;
}
}
}, 24);
<div><b id="found"></b><i id="checking"></i></div>

You are overwriting the innerHTML in every iteration of loop rather than adding to it
Try changing
document.getElementById("fline").innerHTML = '> ' + tempString;
To
document.getElementById("fline").innerHTML += '> ' + tempString;
// ^^ concatenate instead of reassign

Related

Why is my script getting stuck before it reaches the loop?

<div id="content-1"></div>
<div id="content-2"></div>
<div id="content-3"></div>
<script type="text/javascript">
// Write HTML with JS
document.getElementById("content-1").innerHTML = '<h1>Title</h1>...and more';
document.getElementById("content-2").innerHTML = 'hello';
let value = '';
for(let i = 0; i < aR.length; i++){
value += aR[i]['name'] + ": " + aR[i]['price'] + "<br/>";
}
document.getElementById("content-3").innerHTML = 'hi!';
</script>
For some reason my code seems to never reach the third document.getElementById statement. The value for that third statement is supposed to be value not the string hi; I thought the initial problem was with value so I set content-3 as the string "hi" but now I've realized that my script doesn't even run till that point.
Does anyone know what is going on and how to fix it?
as Muhammad Asif said, its aR declare?
for example just add these and will work
var aR = {
0: { name: "XX", price: "55" },
1: { name: "YY", price: "55" }
};
all the code for example
<div id="content-1"></div>
<div id="content-2"></div>
<div id="content-3"></div>
<script type="text/javascript">
var aR = {
0: { name: "XX", price: "55" },
1: { name: "YY", price: "55" }
};
// Write HTML with JS
document.getElementById("content-1").innerHTML = '<h1>Title</h1>...and more';
document.getElementById("content-2").innerHTML = 'hello';
let value = '';
for (let i = 0; i < aR.length; i++) {
value += aR[i]['name'] + ":" + aR[i]['price'] + "<br/>";
}
document.getElementById("content-3").innerHTML = 'hi!';
</script>
by declaring the aR object will run all the code
first of all, only run this line and check whether your script is running or not.
document.getElementById("content-1").innerHTML = '<h1>Title</h1>...and more';
check, is this line is displayed?
second, What is this aR? Did you declare it before?
aR.length;

How to have a button that sorts and another button that reverses the word density of my text?

I don't want to have something like this because it's ugly to see:
But instead, I want my word density to get more organized and sorted out. How do I accomplish all this?
Sort from the highest word density first as a default.
Have a button to reverse (or have the lowest word density first).
And then another button that sorts the highest word density first (like the default).
Here's my HTML:
const displayText = () => {
const inputPage = document.getElementById("input-page");
const countPage = document.getElementById("count-page");
const text = document.getElementById("text");
const textValue = text.value;
if (text.value !== "") {
// normal flow will continue if the text-area is not empty
inputPage.style.display = "none";
document.getElementById("display-text").innerText = textValue;
countPage.style.display = "block";
} else {
// if the text-area is empty, it will issue a warning.
alert("Please enter some text first.");
}
const countWords = (str) => {
return str.split(" ").length;
};
const wordCount = countWords(textValue);
const renderWordCount = () => {
const wordCountDiv = document.getElementById("word-count");
wordCountDiv.innerHTML = "<h1> Words Counted: " + wordCount + "</h1>";
};
const getWordDensity = (str) => {
let wordList = {};
str.split(/[\s.,—–]+/).forEach((word) => { // '\s.,—–' removes space or tab, periods, commas, em and en dashes from the text.
if (typeof wordList[word] == "undefined") {
wordList[word] = 1;
} else {
wordList[word]++;
}
});
return wordList;
};
const wordDensity = getWordDensity(textValue);
const renderWordDensity = () => {
const wordDensityDiv = document.getElementById("word-density");
let table = "<table>";
for (let word in wordDensity) {
table +=
"<tr><td>" + word + "</td><td>" + wordDensity[word] + "</td></tr>";
}
table += "</table>";
wordDensityDiv.innerHTML = "<h1> Word Density: </h1>" + table;
};
renderWordCount();
renderWordDensity();
};
<!DOCTYPE html>
<html>
<head>
<title>Word Counter</title>
</head>
<body>
<div id="input-page">
<h1>Word Counter</h1>
<form action="">
<textarea id="text" type="text" rows="22" cols="60"></textarea>
<br />
</form>
<button onclick="displayText()">COUNT</button>
</div>
<div id="count-page" style="display: none;">
<h1>Your Text:</h1>
<p id="display-text"></p>
<div id="word-count"></div>
<div id="word-density"></div>
</div>
</body>
</html>
Thanks a lot in advance!
You are not going to be able to sort your words correctly, because you are are storing them in an object. Instead store them in an array like this:
wordList = [
{
word: "the",
count: 5,
},{
word: "pizza",
count: 2,
},
]
When you store the data like that, you can sort the array using a custom sort function:
const highestFirst = true;
wordList.sort( (a,b) => {
if( a.count == b.count ) return 0;
if( highestFirst )
return (a.count < b.count) ? -1 : 1;
else
return (a.count > b.count) ? -1 : 1;
});
So have your button run the above function to sort the array, then loop through the array, and for each print out the row. Something like:
var table = document.createElement('table');
wordList.forEach( w => {
let tr = document.createElement('tr');
let td1 = document.createElement('td');
let td2 = document.createElement('td');
td1.innerText = w.word;
td2.innerText = w.count;
tr.appendChild(td1);
tr.appendChild(td2);
table.appendChild(tr);
});

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 sort by alphabetically (ascending and descending) in JavaScript

HTML:
<section class="cd-gallery">
<ul id="courses">
</ul>
<div class="cd-fail-message">No results found</div>
</section>
<ul>
<li><input id="buttonaz" type="button" value="Course name(a-z)"/></li>
<li><input id="buttonza" type="button" value="Course name(z-a)"/></li>
<li><input id="buttonlu" type="button" value="Last updated"></li>
<ul>
JavaScript:
var public_spreadsheet_url = 'https://docs.google.com/spreadsheets/..."
function init() {
Tabletop.init( { key: public_spreadsheet_url,
callback: showInfo,
simpleSheet: true } );
}
window.addEventListener('DOMContentLoaded', init);
function sortAZ(a, b) {
var x = a.Course.toLowerCase();
var y = b.Course.toLowerCase();
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}
function sortZA(a, b) {
var x = a.Course.toLowerCase();
var y = b.Course.toLowerCase();
return ((x > y) ? -1 : ((x < y) ? 1 : 0));
}
function showInfo(data) {
var bodyContent = '';
var sheetUrlRoot = 'https://docs.google.com/spreadsheets/d/';
var buttonaz = document.getElementById("buttonaz");
var buttonza = document.getElementById("buttonza");
console.log(data)
for (var i = 0; i < data.length; i++) {
var sheetUrl = sheetUrlRoot + data[i].ActionId;
var c = data[i].Course;
var courseName = '<div class=\"courseName\">' + c + '</div>';
var designer = data[i]['Designer'].toLowerCase();
var numHolds = data[i]['On Hold']
if (numHolds > 0) {
bodyContent += '<li class="color-2 course mix ' + designer + ' "style="background-color: #E89696";>' + courseName + statusList+ sheetLink+ '</li>';
} else if (numHolds <= 0){
bodyContent += '<li class="color-1 course mix ' + designer + ' "style="background-color: #C2D5BE";>' + courseName + statusList+ sheetLink+'</li>';
}
}
document.getElementById('courses').innerHTML = bodyContent;
document.getElementById('buttonaz').onclick = data.sort(sortAZ);
document.getElementById('buttonaz').onclick = data.sort(sortZA);
}
Hi Stack Overflow users,
I have imported data using tabletop.js to display a set of courses that my university has in hand. However, I cannot have it to display the courses sorting alphabetically from a-z, as well as from z-a when the buttons "Course name (a-z)" and "Course name (z-a)" are clicked. The data are displayed when the page is first loaded, but will not do anything when I click the sorting buttons.
Please help and any input will be appreciated!
P.S. I'm also filtering the courses by the name of designer using mixitup jQuery plugin.
Refer the code which have two button , one is for sort aZ and one is for sort Za . Click on Expand snippet , you will see two button , click on them and enjoy sorting
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Array Sort</h2>
<p>Click the buttons to sort the array alphabetically or numerically.</p>
<button onclick="myFunction1()">Sort Az</button>
<button onclick="myFunction2()">Sort zA</button>
<p id="demo"></p>
<script>
var points = ["z", "b", "d", "a"];
var data1=Array.prototype.slice.call(points);
console.log('Za Sort ',data1.sort().reverse());
document.getElementById("demo").innerHTML = points;
function myFunction1() {
points.sort();
document.getElementById("demo").innerHTML = points;
}
function myFunction2() {
document.getElementById("demo").innerHTML = data1.sort().reverse();
}
</script>
</body>
</html>
If incoming data is array use javascript built in sort() function to sort data
var data = ["z", "b", "d", "a"];
data.sort();
console.log('Ascending order aZ ',data)
data.reverse();
console.log('Descending order zA',data);
output
Ascending order ["a", "b", "d", "z"]
Descending order["z", "d", "b", "a"]
If you want to use library https://underscorejs.org/#
var stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}];
_.sortBy(stooges, 'name');

How do I take text from the text box and use it to implement it in this code?

I'm practicing javascript and learning on my own. I am creating a game where you enter a text coordinates and the game tells you whether you dug something up or not. But I am trying to implement a text box so you can play out of a browser instead of the command prompt, but I'm having trouble getting the game to take the text and then run the code using it when you click on the button.
Here is the HTML for the game.
<head>
<meta charset="UTF-8">
<title>Game Board</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script type="text/javascript" src="board.js"></script>
<script type="text/javascript" src="game.js"></script>
</head>
<body>
<center>
<h1>Archaeology Board</h1>
Palace = 5 Spaces </br>
Temple = 4 Spaces </br>
Forum = 4 Spaces </br>
House = 3 Spaces </br>
Hut = 2 Spaces </br>
<h3>
<table id="board">
</table>
</h3>
<p>
<label for="DigBox">Enter dig coordinates:</label>
<input type="text" id="DigBox" size="3" value="" />
<input type="button" value="Dig" id="run" />
</p>
<p><input type="button" value="Restart Game" id="restart" /></p>
</center>
</body>
</html>
This is the js file to create the board.
function GameBoard()
{
this.ruins = [
{
name: "Palace",
size: 5,
successes: 0
},
{
name: "Temple",
size: 4,
successes: 0
},
{
name: "Forum",
size: 4,
successes: 0
},
{
name: "House",
size: 3,
successes: 0
},
{
name: "Hut",
size: 2,
successes: 0
}
];
this.rows = ["a", "b", "c", "d", "e", "f", "g", "h"];
this.columns = ["1", "2", "3", "4", "5", "6", "7", "8"];
this.cellMarker = 'X';
}
GameBoard.prototype.setBoard = function ()
{
var i, j, boardTags;
boardTags = "";
// build the first row of column labels
boardTags += "<tr><th>&nbsp</th>";
for (j = 0; j < this.columns.length; j++) {
boardTags += "<th>" + this.columns[j] + "</th>";
}
boardTags += "</tr>";
// build the table with HTML tags
for (i = 0; i < this.rows.length; i++) {
boardTags += "<tr>";
boardTags += "<th>" + this.rows[i] + "</th>"; // row labels
for (j = 0; j < this.columns.length; j++) {
boardTags += "<td class='square' id='cell" +
this.rows[i] + this.columns[j] + "'>" + this.cellMarker + "</ td>";
}
boardTags += "</tr>";
}
$("#board").html(boardTags);
for (i = 0; i < this.ruins.length; i++) {
this.setRuin(this.ruins[i]);
}
}
GameBoard.prototype.dig = function(square, processResult)
{
var target, targetObj;
target = $("#cell"+square).attr('ruin');
if (target) {
targetObj = this.getRuin(target);
if (! $("#cell"+square).attr('dug')) {
$("#cell"+square).attr('dug', 'yes');
targetObj.successes++;
}
return targetObj;
}
else {
return undefined;
}
}
GameBoard.prototype.getRuin = function(ruinName)
{
for (var i = 0; i < this.ruins.length; i++) {
if (ruinName === this.ruins[i].name) {
return this.ruins[i];
}
}
return undefined;
}
GameBoard.prototype.randomSquare = function()
{
var colIndex = Math.floor(Math.random() * this.columns.length);
var rowIndex = Math.floor(Math.random() * this.rows.length);
return this.rows[rowIndex] + this.columns[colIndex];
}
GameBoard.prototype.setRuin = function(ruin)
{
// keeps randomly trying to place a ruin until it fits on the board
var candidateSquare = this.randomSquare();
var across = Math.random() < 0.5;
var success = this.tryPlacement(ruin, candidateSquare, across, ruin.size);
while (! success) {
candidateSquare = this.randomSquare();
across = Math.random() < 0.5;
success = this.tryPlacement(ruin, candidateSquare, across, ruin.size);
}
}
GameBoard.prototype.tryPlacement = function(ruin, square, across, size) {
var nextSquare;
if (size === 0) {
// ruin fits!
return true;
}
else if (! square) {
// invalid square
return false;
}
if (! $("#cell" + square).attr('ruin')) {
$("#cell" + square).attr('ruin', ruin.name);
// see if the rest of the ruin fits
if (this.tryPlacement(ruin, this.increment(square, across), across, size - 1)) {
// ruin fits!
return true;
}
else {
// ruin didn't fit --- undo occupied square and return false
$("#cell" + square).removeAttr('ruin');
return false
}
}
}
GameBoard.prototype.increment = function(square, across)
{
if (across) {
// need to increment the column dimension if possible
var colIndex = this.columns.indexOf(square.charAt(1));
colIndex++;
if (colIndex === this.columns.length) {
return undefined;
}
else {
return square.charAt(0) + this.columns[colIndex];
}
}
else {
// need to increment the row dimension if possible
var rowIndex = this.rows.indexOf(square.charAt(0));
rowIndex++;
if (rowIndex === this.rows.length) {
return undefined;
}
else {
return this.rows[rowIndex] + square.charAt(1);
}
}
}
This is the code I'm trying to implement in
$(function () {
tryDig = function(targetCell)
{
var targetObj = board.dig(targetCell);
if (targetObj) {
alert('Success finding the ' + targetObj.name);
$("#cell"+targetCell).html('#');
$("#cell"+targetCell).css('color', 'blue');
}
else {
alert('Failure!');
$("#cell"+targetCell).html('*').css('color', 'red');
}
}
board = new GameBoard();
board.setBoard();
});
initialize = function() {
$("#run").click(tryDig);
}
initialize = function() {
$("#restart").click(GameBoard.prototype.setBoard);
}
$(initialize);
I want to make it so whatever is in the text box, the game uses that as the coordinates to dig up in the board.

Categories