Alright, in my results for my program the results are displayed in a horizontal list (for e.x, HI,HELLO,HI,HELLO). I am trying to get these results to be in a numbered list from top to bottom.
function button() {
var inputArray = [];
var size = 4;
for (var i = 0; i < size; i++) {
inputArray[i] = prompt('Enter Element ' + (i + 1));
inputArray.sort();
document.getElementById("demo").innerHTML =
inputArray.map(function(x) {
return x.toUpperCase()
});
}
var str = String(inputArray).toUpperCase().split(",");
}
<button onclick="button();">Array</button>
<p id="demo"></p>
https://repl.it/repls/DangerousCloudyNumber
Just use an ordered list (<ol>) instead of a paragraph (<p>) and add list items (<li>) to the values while mapping them:
function button(){
var inputArray = [];
var size = 4;
for(var i=0; i<size; i++) {
inputArray[i] = prompt('Enter Element ' + (i+1));
inputArray.sort();
document.getElementById("demo").innerHTML = inputArray.map(function(x){ return "<li>"+x.toUpperCase()+"</li>"}).join("");
}
var str = String(inputArray).toUpperCase().split(",");
}
<!DOCTYPE html>
<html>
<head>
<script src="script.js"></script>
<meta charset="utf-8">
<title>Program</title>
</head>
<body>
<button onclick="button();">Array</button>
<ol id="demo"></ol>
</body>
</html>
function button(){
var inputArray = [];
var size = 4;
var final_html = "<ol>"
for(var i=0; i<size; i++) {
input = prompt('Enter Element ' + (i+1));
if (input === null) {
document.getElementById("demo").innerHTML = inputArray.map(function(x){
if (x != null) {
final_html = final_html +"<li>"+x.toUpperCase()+"</li>";
}
});
document.getElementById("demo").innerHTML = final_html;
return; //break out of the function early
}else{
inputArray[i] = input;
}
inputArray.sort();
}
}
Related
I am trying to compare the elements inside my unordered list to the value in the input textbox. If the value in the input text box matches a word in the unordered list I want to do something with that word in the unordered list.
Here is my JavaScript code:
function CheckWordMatch() {
var wordList = document.getElementById("wordSearchTable");
var wordListLi = wordList.getElementsByTagName("li");
var inputBoxText = document.getElementById("pickedLetters");
for (var i = 0; i < wordListLi.length; i++) {
if (inputBoxText.value === wordListLi[i].value) {
wordArray.style.textDecoration = "line-through";
console.log("IT WORKS");
}
}
}
#wordSearchTable is the ID of the unordered list.
#pickedLetters is the ID of the input text box.
Here is the entire javascript code and html code:
var allCells;
var found = false;
window.onload = init;
function init() {
document.querySelectorAll("aside h1")[0].innerHTML = wordSearchTitle;
document.getElementById("wordTable").innerHTML = drawWordSearch(letterGrid, wordGrid);
document.getElementById("wordList").innerHTML = showList(wordArray);
allCells = document.querySelectorAll("table#wordSearchTable td");
for (var i = 0; i < allCells.length; i++) {
allCells[i].addEventListener("mousedown", highlightLetters)
allCells[i].style.cursor = "pointer";
allCells[i].addEventListener("mouseup", removeMouseDown)
}
document.getElementById("pickedLetters").addEventListener('keyup', CheckWordMatch);
//document.getElementById("wordTable").addEventListener("mouseup", CheckWordMatch);
console.log("Hello");
}
/*============================================================*/
function drawWordSearch(letters, words) {
var rowSize = letters.length;
var colSize = letters[0].length;
var htmlCode = "<table id='wordSearchTable'>";
htmlCode += "<caption>Word Search</caption>";
for (var i = 0; i < rowSize; i++) {
htmlCode += "<tr>";
for (var j = 0; j < colSize; j++) {
if (words[i][j] == " ") {
htmlCode += "<td>";
} else {
htmlCode += "<td class='wordCell'>";
}
htmlCode += letters[i][j];
htmlCode += "</td>";
}
htmlCode += "</tr>";
}
htmlCode += "</table>";
return htmlCode;
}
function showList(list) {
var htmlCode = "<ul id='wordSearchList'>";
for (var i = 0; i < list.length; i++) {
htmlCode += "<li>" + list[i] + "</li>";
}
htmlCode += "</ul>";
return htmlCode;
}
function removeMouseDown(e) {
for (var i = 0; i < allCells.length; i++) {
allCells[i].removeEventListener("mouseenter", highlightLetters2)
}
CheckWordMatch();
}
function highlightLetters2(e) {
var inputBoxValue = document.getElementById("pickedLetters");
e.target.style.backgroundColor = "pink";
inputBoxValue.value = inputBoxValue.value + e.target.textContent;
for (var i = 0; i < allCells.length; i++) {
allCells[i].addEventListener("mouseup", removeMouseDown)
}
}
function highlightLetters(e) {
var inputBoxValue = document.getElementById("pickedLetters");
e.target.style.backgroundColor = "pink";
inputBoxValue.value = e.target.textContent;
for (var i = 0; i < allCells.length; i++) {
allCells[i].addEventListener("mouseenter", highlightLetters2)
}
}
function CheckWordMatch(event) {
var inputBoxText = event.target.value;
var wordList = document.getElementById("wordSearchTable");
var wordListLi = wordList.getElementsByTagName("li");
var inputBoxText = document.getElementById("pickedLetters");
for (var i = 0; i < wordListLi.length; i++) {
if (inputBoxText.value === wordListLi[i].textContent) {
wordArray.style.textDecoration = "line-through";
console.log("IT WORKS");
}
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Word Search</title>
<meta charset="utf-8" />
<link href="p2-layout.css" rel="stylesheet" />
<script src="p2-makeTable.js" async></script>
<script src="p2-wordSearch.js" async></script>
</head>
<body>
<section id="main">
<header><br></header>
<article>
<figure id="wordTable"></figure>
<input type="button" value="Show Solution" id="showSolution" />
</article>
<aside>
<h1 id="wordSearchTitle"></h1>
<input type="text" id="pickedLetters" readonly />
<figure id="wordList"></figure>
</aside>
</section>
</body>
</html>
First you'll need to attach an event listener to the input element #pickedLetters. I used keyup in this example but feel free to pick what suits your use-case best.
document.getElementById("pickedLetters").addEventListener('keyup', CheckWordMatch);
I also fixed some of your sample code. See below with comments:
function CheckWordMatch(event) {
// get the value of the target which is the value of the input element.
var inputBoxText = event.target.value;
var wordList = document.getElementById("wordSearchTable");
var wordListLi = wordList.getElementsByTagName("li");
for (var i = 0; i < wordListLi.length; i++) {
// since you want to compare the value of the input
// element with the value (or text) of the li element,
//you should use textContent or innerText.
if (inputBoxText === wordListLi[i].textContent) {
wordListLi[i].style.textDecoration = "line-through";
console.log("IT WORKS");
}
}
}
// attach an event listener to the input element to trigger your function.
document.getElementById("pickedLetters").addEventListener('keyup', CheckWordMatch);
I need to make a for loop that repeats the letter "E" in any word written in a prompt by the user.
For example if the person writes "several" it should print "seveeeral" or if the user writes "example" it should print "xampleeeeee"
my Html code is this
<html>
<head>
<script src="practice1.js"></script>
<title>My practice</title>
</head>
<body>
<h2>My example</h2>
<p id="letterEOutput">Output</p>
<button onclick="letterE()">Make E's</button>
</body>
</html>
and this is what I have so far with the JS, but I don't know what else to do
I want to use a for loop, and the "x.repeat(y)"
function letterE(){
let many = prompt("Enter your text");
let letters = "";
for (let i=0; i<many.length; i++){
letters += text.charAt(i);
}
document.getElementById("letterEOutput").innerHTML = final;
}
Try it:
function repeatLetter(entry, letter, times) {
let text = "";
let textRepeated = "";
for (let i = 0; i < times; i++) {
textRepeated += letter;
}
for (let i = 0; i < entry.length; i++) {
if (entry[i] === letterRepeated) {
text += textRepeated;
} else {
text += entry[i];
}
}
return text;
}
const entry = "Enter your text";
const letterRepeated = "e";
const repeatTimes = 5;
const result = repeatLetter(entry, letterRepeated, repeatTimes);
console.log(result);
Need help with assignment. I need to create a button that uses a for loop to multiply each number in the array by the number after it into a second array and display the result. Lastly create another button that uses a while loop that divides each number in the array by the number after it into a third array and once more display the result. I have created a way to input numbers into an array "numbers" and display the array but do not know how to use for loops to display the quotient nor the product please help :(
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<input type="number" id="num" min="0" max="100">
<button onclick="myFunction()">Try it</button>
<button onclick="SortFunction()">Sort it</button>
<button onclick="AddFunction()">Add it</button>
<p id="demo"></p>
<script>
var myarray =[] ;
var text ;
function myFunction()
{
var fLen ;
var x = document.getElementById("num").value;
var i ;
myarray.push(Number(x));
fLen = myarray.length ;
text = "<ul>";
for (i = 0; i < fLen; i++)
{
text += "<li>" + myarray[i] + "</li>";
}
text += "</ul>";
document.getElementById("demo").innerHTML = text;
}
function SortFunction()
{
myarray.sort(function(a, b){return a - b});
document.getElementById("demo").innerHTML = myarray;
}
function AddFunction()
{
var sum = 0 ;
var fLen ;
var i ;
fLen = myarray.length ;
for (i = 0; i < fLen; i++)
{
sum = sum + Number(myarray[i]);
}
document.getElementById("demo").innerHTML = sum;
}
</script>
Well, simply you could add these buttons and try to create some special logic for each button inside relevant function, for example MultiplyNumbers() and DivideNumbers():
<button onclick="MultiplyNumbers()">Multiply pairs</button>
<button onclick="DivideNumbers()">Divide pairs</button>
In both functions firstly you should check if the main array has paired values via dividing length with 2 -> length % 2 == 0, then check if they're valid numbers with isNaN() function, if some value in pair is not valid you can define the result of this math equal 0 or what you want. Dividing function request also checking the second value in each pair with 0, cause you can't divide a number with zero(or you can).
So, the first function works via for loop, the second one via while loop.
The snippet below shows you this two functions, they're work correctly with this simple rules. If I've missed something you can tell me.
var myarray =[] ;
var text ;
function myFunction()
{
var fLen ;
var x = document.getElementById("num").value;
var i ;
myarray.push(Number(x));
fLen = myarray.length ;
text = "<ul>";
for (i = 0; i < fLen; i++)
{
text += "<li>" + myarray[i] + "</li>";
}
text += "</ul>";
document.getElementById("demo").innerHTML = text;
}
function SortFunction()
{
myarray.sort(function(a, b){return a - b});
document.getElementById("demo").innerHTML = myarray;
}
function AddFunction()
{
var sum = 0 ;
var fLen ;
var i ;
fLen = myarray.length ;
for (i = 0; i < fLen; i++)
{
sum = sum + Number(myarray[i]);
}
document.getElementById("demo").innerHTML = sum;
}
function MultiplyNumbers() {
let multNumbers = [];
if (myarray.length % 2 == 0){
let actions = myarray.length / 2;
for(let i = 0; i < actions; i++){
var tmult = (isNaN(myarray[i*2]) || isNaN(myarray[i*2+1])) ?
0 :
Number(myarray[i*2]) * Number(myarray[i*2+1]);
multNumbers.push(tmult);
}
document.getElementById("demo").innerHTML = multNumbers;
}
}
function DivideNumbers() {
let divNumbers = [];
if (myarray.length % 2 == 0){
let actions = myarray.length / 2;
let i = 0;
while(i<actions){
var tdiv = (isNaN(myarray[i*2]) || isNaN(myarray[i*2+1]) || Number(myarray[i*2+1]) == 0) ?
0 :
Number(myarray[i*2]) / Number(myarray[i*2+1]);
divNumbers.push(tdiv);
i++;
}
document.getElementById("demo").innerHTML = divNumbers;
}
}
<input type="number" id="num" min="0" max="100">
<button onclick="myFunction()">Try it</button>
<button onclick="SortFunction()">Sort it</button>
<button onclick="AddFunction()">Add it</button>
<button onclick="MultiplyNumbers()">Multiply pairs</button>
<button onclick="DivideNumbers()">Divide pairs</button>
<p id="demo"></p>
var myarray =[] ;
var text ;
function myFunction()
{
var fLen ;
var x = document.getElementById("num").value;
var i ;
myarray.push(Number(x));
fLen = myarray.length ;
text = "<ul>";
for (i = 0; i < fLen; i++)
{
text += "<li>" + myarray[i] + "</li>";
}
text += "</ul>";
document.getElementById("demo").innerHTML = text;
}
function SortFunction()
{
myarray.sort(function(a, b){return a - b});
document.getElementById("demo").innerHTML = myarray;
}
function AddFunction()
{
var sum = 0 ;
var fLen ;
var i ;
fLen = myarray.length ;
for (i = 0; i < fLen; i++)
{
sum = sum + Number(myarray[i]);
}
document.getElementById("demo").innerHTML = sum;
}
// updated code
var secondArray=[];
function multiplyFunction(){
var temp = document.getElementById("num").value;
for(i=0;i<myarray.length;i++){
secondArray.push(Number(temp) * myarray[i]);
}
// show new array ..
text = "<ul>";
for (i = 0; i < myarray.length; i++){
text += "<li>" + secondArray[i] + "</li>";
}
text += "</ul>";
document.getElementById("demo").innerHTML = text;
//
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<input type="number" id="num" min="0" max="100">
<button onclick="myFunction()">Try it</button>
<button onclick="SortFunction()">Sort it</button>
<button onclick="AddFunction()">Add it</button>
<button onclick="multiplyFunction()">Multiply</button>
<button onclick="divideFunction()">Divide</button>
<p id="demo"></p>
</body>
</html>
i have some code that takes input numbers and put them into a new array. How can i make it so my alert tells the user how many times the number is represented in the input? Exampel 0,4,4,2,3,4,1 would show "0 appears 1 time, 4 appears 3 times" and so on...I think im close but cant get the final part right...
<!DOCTYPE html>
<html>
<head>
<title>Oppgave 5</title>
<script type="text/javascript">
window.onload = btn;
function btn() {
document.getElementById("btn").onclick = showTxt;
}
function showTxt() {
var text = "";
var input = document.getElementById("input").value;
var split = input.split(",");
var newArray = split;
var count = 0;
for (var i = 0; i < newArray.length; i++) {
if (newArray[i] === parseInt(input)) {
count++;
}
alert("Number " + newArray[i] + " appears " + count + " times");
}
text += newArray;
document.getElementById("print").innerHTML = text;
}
</script>
</head>
<body>
<input id="input" type="text">
<button id="btn" type="button">Show</button>
<p id="print"></p>
</body>
</html>
I have changed your showTxt function
function showTxt() {
var text = "";
var input = document.getElementById("input").value;
var split = input.split(",");
var newArray = split;
var count;
for (var i = 0; i < newArray.length; i++) {
count = 0;
for (var j = 0; j < newArray.length; j++) {
if (newArray[i] === newArray[j]) {
count++;
}
}
alert("Number " + newArray[i] + " appears " + count + " times");
}
text += newArray;
document.getElementById("print").innerHTML = text;
}
You could use the method from this gist like so:
window.onload = btn;
function btn() {
document.getElementById("btn").onclick = showTxt;
}
function showTxt() {
var text = "";
var input = document.getElementById("input").value;
var split = input.replace(/ /g, '').split(",").sort();
compressArray(split);
}
function compressArray(original) {
var compressed = [];
// make a copy of the input array
var copy = original.slice(0);
// first loop goes over every element
for (var i = 0; i < original.length; i++) {
var myCount = 0;
// loop over every element in the copy and see if it's the same
for (var w = 0; w < copy.length; w++) {
if (original[i] == copy[w]) {
// increase amount of times duplicate is found
myCount++;
// sets item to undefined
delete copy[w];
}
}
if (myCount > 0) {
var a = new Object();
a.value = original[i];
a.count = myCount;
compressed.push(a);
}
}
for (var i = 0; i < compressed.length; i++) {
var message = compressed[i].value + ' appears ' + compressed[i].count + ' times.';
alert(message);
document.getElementById("print").innerHTML += message + '</br>';
}
};
<input id="input" type="text">
<button id="btn" type="button">Show</button>
<p id="print"></p>
Check this out, may be it'll helpful .
<!DOCTYPE html>
<html>
<head>
<title>Oppgave 5</title>
<script type="text/javascript">
window.onload = btn;
function btn() {
document.getElementById("btn").onclick = showTxt;
}
function showTxt() {
var text = "";
var input = document.getElementById("input").value;
var split = input.split(",");
var newArray = split;
let countedValues = newArray.reduce(function(obj,val){
if(obj[val])
obj[val] += 1;
else
obj[val] = 1;
return obj
}, {})
for (let value in countedValues ) {
alert("Number " + value + " appears " + countedValues[value] + " times");
}
text = newArray;
document.getElementById("print").innerHTML = text;
}
</script>
</head>
<body>
<input id="input" type="text">
<button id="btn" type="button">Show</button>
<p id="print"></p>
</body>
</html>
Here is the error I get:
Here is the code:
<html>
<head>
</head>
<body>
<p> Please enter a series of numbers, each separated by a new line.<br><p>
<textarea id="myTextArea" rows = "7" cols = "50"></textarea><br>
<button onclick="processData()">Done</button>
<p id = "mean"></p>
<p id = "median"></p>
<p id = "count"></p>
<p id = "summation"></p>
<p id = "mode"></p>
<p id = "variance"></p>
<p id = "sd"></p>
<script type = "text/javascript">
function processData()
{
var arrayOfLines = document.getElementById('myTextArea').value.split('\n');
var length = arrayOfLines.length;
var modeArr = {};
var sum = 0;
var mean = 0;
var median = 0;
var count = length;
var mode = 0;
var variance = 0;
var standard deviation = 0;
var modeCounter = {};
var meanOutput = document.getElementById('mean');
var medianOutput = document.getElementById('median');
var modeOutput = document.getElementById('mode');
var countOutput = document.getElementById('count');
var summationOutput = document.getElementById('summation');
var varianceOutput = document.getElementById('variance');
var sdOutput = document.getElementById('sd');
alert("hi");
alert(arrayOfLines[0]);
sum(arrayOfLines);
mean(arrayOfLines);
median(arrayOfLines);
mode(arrayOfLines);
variance(arrayOfLines);
standardDeviation(arrayOfLines);
variance(arrayOfLines);
}
function sum(array)
{
for (var a = 0; a < length; a++)
{
sum += arrayOfLines[a];
}
alert(sum);
summationOutput.innerHTML = sum;
}
function mode (array)
{
for (var a = 0; a < length; a++)
{
for (var b = 0; b < modeArr.length; b++)
{
if (arr[a] == arr[b])
{
modeCounter[a]++;
}
}
arr[a] = arrayOfLines[a];
}
moedOutput.innerHTML = mode;
}
function mean (array)
{
mean = sum/length;
meanOutput.innerHTML = mean;
}
function median (array)
{
if (length % 2 == 1)
{
median = sortedArrayOfLines[((length - 1)/2)+1]
}
else
{
median = (sortedArrayOfLines[length/2] + sortedArrayOfLines[(length/2)+1])/2
}
medianOutput.innerHTML = median;
}
function variance (array)
{
var mean = mean(array);
return mean(array.map(function(num)
{
varianceOutput.innerHTML = Math.pow(num - mean, 2);
}));
}
function standardDeviation (array)
{
medianOutput.innerHTML = Math.sqrt(variance(array));
}
</script>
</body>
</html>
problem is here
var standard deviation = 0;
^^
replace it with
var standard_deviation = 0;