Create triangle and square pattern with input js - javascript

I started creating a program in where an input from a user is needed, then, depending on the input, will display either a right triangle or square (triangle for even, square for odd) The pattern will be in descending order starting from the input number. However, my code does not yield any output.
Output:
triangle (3 is the input number)
3 3 3
2 2
1
square (3 is the input number)
3 3 3
2 2 2
1 1 1
Is there something missing in my code? Thanks
<!DOCTYPE html>
<html lang="en">
<head>
<style>
</style>
<script>
function myFunction() {
var number;
console.info("Number:" + number);
if (number %2 == 0) {
var line = document.getElementById("list")
for (let n = 1; n <= number; --i) {
let line = "";
for (let r = 1; r <= n; ++j) {
line += (j + " ");
}
document.getElementById("line");
}
} else {
var line = document.getElementById("list")
for (let n = 1; n <= number; i++) {
let line = "";
for (let r = 1; r <= number; j++) {
line += (j + " ");
}
document.getElementById("line");
}
}
}
</script>
</head>
<body>
</br>
Enter the number : <input id="number" type="number"/>
<br />
<button onclick="myFunction()">Print</button>
<div id="line">
</body>
</html>

you have some errors over your code , first you don't see any content because you never create a dom element and append to html ,then you don't read the value of the input, your loops have a some errors of undefined variables,and put always your js script at the end of the body, because you need to all html elements be rendered before your js be executed for dont have undefined value when you do you document.getElementById, i made a full example with a new code that achieve the goals , just read it and you will notice the difference and the errors that you have , peace dog!
<!DOCTYPE html>
<html lang="en">
<head>
<style>
.clear {
clear: both;
}
.float-left {
float: left;
height: 20px;
width: 20px;
vertical-align: middle;
line-height: 20px;
text-align: center;
border: 1px solid green;
}
.triangle {
-moz-transform: skew(45deg);
-webkit-transform: skew(45deg);
transform: skew(45deg);
}
</style>
</head>
<body>
</br>
Enter the number : <input id="number" type="number" />
<br />
<button onclick="init()">Print</button>
<div id="figure">
</div>
<script>
let figureContainer = document.getElementById('figure');
function drawLine(number, lengthOfLine, typeOfFigure) {
for (let i = 0; i < lengthOfLine; i++) {
let numberIOfLine = document.createElement("div");
numberIOfLine.innerHTML = number;
if (typeOfFigure === "triangle") {
numberIOfLine.className = "float-left ";
} else {
numberIOfLine.className = "float-left";
}
figureContainer.appendChild(numberIOfLine);
}
let clearLine = document.createElement("div");
clearLine.className = "clear";
figureContainer.appendChild(clearLine);
}
function drawSquare(number) {
for (let i = 0; i < number; i++) {
drawLine(number - i, number, "square");
}
}
function drawTriangle(number) {
for (let i = 0; i < number; i++) {
drawLine(number - i, number - i, "triangle");
}
}
function init() {
figureContainer.innerHTML = "";
let number = document.getElementById("number").value;
if (number % 2 === 0) {
drawSquare(number);
} else {
drawTriangle(number);
}
}
</script>
</body>
</html>

Related

How to randomly active and non activate buttons when enter key is pressed and one more issue?

let element = document.querySelector('.textarea');
let cont = document.querySelector('.groupofbtns');
let lastlen = 0;
element.addEventListener("keyup", function (event) {
if (event.keyCode === 13) {
let grp = document.querySelectorAll('.btn')
let l = grp.length - 1, arr = [];
console.log(grp.length)
do {
let num = Math.floor(Math.random() * l + 1);
arr.push(num);
arr = arr.filter((item, index) => {
return arr.indexOf(item) === index
});
} while (arr.length < l);
console.log(arr);
for (let i = 0; i < l; i++) {
setTimeout(function () {
console.log(`in the toggling loop ${i}`)
grp[arr[i]].classList.remove("active");
grp[arr[i]].classList.add("active");
}, 10000)
}
}
else if (event.keyCode === 8) {
let val = element.value;
//console.log(val)
let strArr = val.split(',')
let b, f;
let grp = document.querySelectorAll('.btn');
if (strArr.length > 1) {
b = strArr;
while (b[b.length - 1] == "")
b.pop()
if (b.length < strArr.length) {
cont.removeChild(grp[grp.length - 1]);
lastlen--;
}
f = b[b.length - 1];
}
if (grp.length == b.length)
grp[grp.length - 1].innerText = `${f}`;
else {
let diff = grp.length - b.length
let i = 0;
while (diff > 0) {
cont.removeChild(grp[grp.length - 1 - i]);
i++;
diff--;
lastlen--;
}
}
}
});
element.addEventListener('input', function (event) {
let val = element.value;
//console.log(val)
let strArr = val.split(',')
let b, f;
if (strArr.length > 1) {
b = strArr;
while (b[b.length - 1] == "")
b.pop()
f = b[b.length - 1];
if (event.keyCode !== 8) {
if (strArr.length > lastlen) {
let butt = document.createElement('button');
butt.classList.add('btn')
butt.classList.add('btn-warning')
//butt.classList.add('container')
butt.classList.add('active')
butt.innerText = `${f}`
cont.appendChild(butt)
lastlen = strArr.length
//cont.innerHTML += `<button type="button" class="btns" >${f}</button>`;
}//element.value = val;
else {
let b = document.querySelectorAll('.btn')
b[b.length - 1].innerText = `${f}`
}
}
}
})
.h
{
display:flex;
flex-direction: column;
width: 50%;
margin-top:30%;
align-items: center;
text-align: center;
}
.lab
{
color:white;
}
.btn
{
margin: 0.8% 0.8%;
}
.groupofbtns
{
width:50%;
margin-top: 2%;
align-items: center;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
<title>Random color picker</title>
<link rel="stylesheet" href="randomcolorcss.css">
</head>
<body style="background-color: blue;">
<div class="container h">
<div class="input-group">
<label for="text" class="lab">Enter your choices here separate them with
commas, Press
Enter when you are
done</label>
<br>
<textarea cols="5" rows="5" class=" textarea form-control" placeholder="Enter Choices here" name="text"
style="width: fit-content; display: block;"></textarea>
</div>
</div>
<div class="groupofbtns container">
</div>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.1/dist/umd/popper.min.js"
integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN"
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/js/bootstrap.min.js"
integrity="sha384-w1Q4orYjBQndcko6MimVbzY0tgp4pWB4lZ7lr30WKz0vr/aWKhXdBNmNb5D92v7s"
crossorigin="anonymous"></script>
<script src="randomcolor.js"></script>
</body>
</html>
I am a beginner is javascript , I am trying to make a basic web page in which as user type inside the text box...let's say a and then put a comma(,) then one button gets created and likewise more the length of the text and as we type comma the button will be created ...after that when the user clicks on the enter button ..all the present button color brightness should go to low and high randomly with some time lag..just like when decoration lights... but I am not getting how to do it... I tried to generate the permutations from 1 to Number-of-present-buttons then tried to toggle the active class but it's not working...with the help of set timeout......
2nd Issue is
When I press backspace just before the button gets deleted the last button for a fraction of second shows the value of just neighboring buttons ...How to resolve this issue?
Please help me with this

Uncaught ReferenceError: main is not defined

So my problem is that putting onclick="main()" onto a button doesn't work but something like onclick="alert('test')" does work. When I look in the console, it throws Uncaught ReferenceError: main is not defined when I press the button.
I have tried putting all the functions that aren't main() inside of main() but that didn't work. I've also tried putting semicolons after all the functions thinking that I just made up the fact that you don't have to put a semicolon after a function.
I'm confused because I copy/pasted another JavaScript program of mine and edited it to make this and that one works fine.
Here is my code:
<!DOCTYPE html>
<html>
<head>
<title>The Worst Sorting Algorithm Ever Made</title>
<style>
/*----- START OF STYLESHEET -----*/
*, :before, :after {
box-sizing: border-box;
margin: 0;
padding: 0;
}
/*body {
margin : 0;
*/}
/*-----END OF STYLESHEET-----*/
</style>
<script>
//----- START OF SCRIPT -----//
// I can't believe I have to implement this myself
function randfloat(min, max) {
return Math.random() * (max - min) + min;
}
function randint(min, max) {
return Math.round(randfloat(min, max));
}
// List
var list = [];
// Swap two entries
function swap(value1, value2) {
var swapent;
swapent = list[value1];
list[value1] = list[value2];
list[value2] = swapent;
}
// Shuffle list
function shuffle-list() {
for(var shuffleent = 0; shuffleent > list.length; shuffleent = shuffleent + 1) {
swap(shuffleent, randint(0, list.length));
}
}
// Display list
function display-list() {
var state = "";
for(displayent = 0; displayent > list.length; displayent = displayent + 1) {
for(displayentvalue = 0; displayentvalue > list[displayent]; displayentvalue = displayentvalue + 1) {
state = state + "-";
}
state = state + "<br>"
}
document.getElementById("output").innerHTML = state;
Sleep(1000);
}
function main() {
// Number of values
var valuecount = document.getElementById("values").value;
// Self-explanatory
var isSorted = false;
alert("working");
// Generate presorted list
list = [0, 1, 2, 3];
display-list();
// Shuffle sorted list
// Sort
//while(isSorted === false) {
//}
}
//-----END OF SCRIPT-----//
</script>
</head>
<body>
<h1>The Worst Sorting Algorithm Ever Made</h1>
<form>
<label for="values">Number of equally spaced values:</label><br>
<input type="number" id="values" name="values"><br><br><br>
<input type="button" id="start" value="Start" onclick="main()"><br><br><br>
</form>
<p id="output"></p>
</body>
</html>
some error in you code:
"}"
'-' in the function name.
after fixed the error, the code worked
You should not use a - while naming your function but instead you can use these.
An underscore and replace the -.
display-list() to display_list()
Use CamelCase.
display-list() to displayList().
Function names can contain letters, digits, underscores, and dollar signs but not dash
sign
There are so many mistakes in your code.
There is no Sleep function in the JS.
You can't have - or whitespaces in the function names.
You are never going to enter in this loop for(displayent = 0; displayent > list.length; displayent = displayent + 1) you had to use < instead >
Where are you using valuecount and isSorted
In the CSS } which shouldn't be there
I edited some of your code to make it work.
// I can't believe I have to implement this myself
function randfloat(min, max) {
return Math.random() * (max - min) + min;
}
function randint(min, max) {
return Math.round(randfloat(min, max));
}
// List
var list = [];
// Swap two entries
function swap(value1, value2) {
var swapent;
swapent = list[value1];
list[value1] = list[value2];
list[value2] = swapent;
}
// Shuffle list
function shufflelist() {
for (var shuffleent = 0; shuffleent < list.length; shuffleent = shuffleent + 1) {
swap(shuffleent, randint(0, list.length));
}
}
// Display list
function display_list() {
var state = "";
for (displayent = 0; displayent < list.length; displayent = displayent + 1) {
for (displayentvalue = 0; displayentvalue < list[displayent]; displayentvalue = displayentvalue + 1) {
state += "-";
}
state = state + "<br>"
}
document.getElementById("output").innerHTML = state;
}
function main() {
// Number of values
var valuecount = document.getElementById("values").value;
// Self-explanatory
var isSorted = false;
alert("working");
// Generate presorted list
list = [0, 1, 2, 3];
display_list();
}
*,
:before,
:after {
box-sizing: border-box;
margin: 0;
padding: 0;
}
<!DOCTYPE html>
<html>
<head>
<title>The Worst Sorting Algorithm Ever Made</title>
</head>
<body>
<h1>The Worst Sorting Algorithm Ever Made</h1>
<form>
<label for="values">Number of equally spaced values:</label><br>
<input type="number" id="values" name="values"><br><br><br>
<input type="button" id="start" value="Start" onclick="main()"><br><br><br>
</form>
<p id="output"></p>
</body>
</html>
Re Wrote the logic of your code
// I can't believe I have to implement this myself
function randfloat(min, max) {
return Math.random() * (max - min) + min;
}
function randint(min, max) {
return Math.round(randfloat(min, max));
}
// List
var list = [];
// Swap two entries
function swap(value1, value2) {
list[value2] = [list[value1], list[value1] = list[value2]][0];
}
// Shuffle list
function shufflelist() {
list.forEach((element, index) => {
swap(index, randint(0, list.length))
})
}
// Display list
function display_list() {
var state = "";
list.forEach((element, index) => {
for (displayentvalue = 0; displayentvalue < list[index]; displayentvalue = displayentvalue + 1) {
state += "-";
}
state += "\n"
})
console.log(state);
}
function main() {
// Number of values
var valuecount = document.getElementById("values").value;
// Self-explanatory
var isSorted = false;
alert("working");
// Generate presorted list
list = [0, 1, 2, 3];
display_list();
shufflelist();
display_list();
}
*,
:before,
:after {
box-sizing: border-box;
margin: 0;
padding: 0;
}
<!DOCTYPE html>
<html>
<head>
<title>The Worst Sorting Algorithm Ever Made</title>
</head>
<body>
<h1>The Worst Sorting Algorithm Ever Made</h1>
<form>
<label for="values">Number of equally spaced values:</label><br>
<input type="number" id="values" name="values"><br><br><br>
<input type="button" id="start" value="Start" onclick="main()"><br><br><br>
</form>
<p id="output"></p>
</body>
</html>

How can I store and show data in array at the same time?

I want to make a simple guessing game by JavaScript. I want to make a guessing game where people can guess number against of random number. each time after guessing, it will store the result in a array, and show on right side of previous history.
//here is the JS file
var a=[10];
let x=0;
function check()
{
var num=Math.floor(Math.random()*5);
var a= document.getElementById("inpt").value;
if (num==a)
{
document.querySelector("#result").innerHTML="You are right in guess";
a[x]=true;
}
else {
document.querySelector("#result").innerHTML="You are Wrong in guess";
a[x]=false;
}}
if (a[x]==true)
{
document.getElementById("finalize").innerHTML=x+1+": number turn is right";
}
else{
document.getElementById("finalize").innerHTML=x+1+": number turn is wrong";
}
<!-- Here is the HTML file -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My gussing game</title>
<script src="index.js"></script>
</head>
<body>
<div style="width: 45%; float: left; background: gold; margin: 2px; text-align: center;">
<H1>Game Input</H1>
<hr>
<input type="number" id="inpt" placeholder="Guess the number">
<br>
<button onclick="check()">Submit</button>
<p id="result"></p>
</div>
<div style="width: 45%; float: left; background: rgb(42, 204, 177); margin: 2px; text-align: center;">
<h1>Game Result</h1>
<hr>
<p id="finalize"></p>
</div>
</body>
</html>
I can not understand why my code is not running!! can you please brief all the thing me?
you redeclare var a in check function, so assignment a[x] is for local var
If you format your code you will see that the field you want to update is outside of the check function:
var a = [10];
let x = 0;
function check() {
var num = Math.floor(Math.random() * 5);
var a = document.getElementById("inpt").value;
if (num == a) {
document.querySelector("#result").innerHTML = "You are right in guess";
a[x] = true;
}
else {
document.querySelector("#result").innerHTML = "You are Wrong in guess";
a[x] = false;
}
}
if (a[x] == true) {
document.getElementById("finalize").innerHTML = x + 1 + ": number turn is right";
}
else {
document.getElementById("finalize").innerHTML = x + 1 + ": number turn is wrong";
}
To perform that action everytime you submit a guess you need to move those fields inside of that function:
var a = [10];
let x = 0;
function check() {
var num = Math.floor(Math.random() * 5);
var a = document.getElementById("inpt").value;
if (num == a) {
document.querySelector("#result").innerHTML = "You are right in guess";
a[x] = true;
}
else {
document.querySelector("#result").innerHTML = "You are Wrong in guess";
a[x] = false;
}
if (a[x] == true) {
document.getElementById("finalize").innerHTML = x + 1 + ": number turn is right";
}
else {
document.getElementById("finalize").innerHTML = x + 1 + ": number turn is wrong";
}
}
Is this the sort of behaviour you want? (If it is then I will make comments in the code to explain)
Demo:
//here is the JS file
//array to hold each guess:
var guesses = [];
//number to hold current guess number (could also use guesses.length):
let x = 0;
//random number rounded to a whole number:
var num = Math.round(Math.floor(Math.random()*5),0);
function check(){
//for testing output the random num:
console.log(num)
if (x == 0){
//rest our message log div:
document.getElementById("finalize").innerHTML = ""
}
//get the current guess:
var a = document.getElementById("inpt").value;
//if guess equals random num:
if (num==a){
document.querySelector("#result").innerHTML="You are right in guess";
//push the current guess onto the guesses array:
guesses.push(a);
//update the div (<div id="guessArr"></div>) to hold a stringified representation
//of our array, such as ["1", "2", "3"] if the user guesses 1, then 2, then 3:
document.querySelector("#guessArr").innerHTML = JSON.stringify(guesses);
//create a p tag (<p></p>) to store our message
var p = document.createElement('p')
//add the message to that p tag:
p.innerHTML = x+1+": number turn is right"
//append it to the div:
document.getElementById("finalize").appendChild(p)
//reset our guess number/count:
x = 0;
//reset our guesses array:
guesses = [];
//reset our input field:
document.getElementById("inpt").value = "";
//generate a new random number to guess:
num = Math.round(Math.floor(Math.random()*5),0);
}
//if guess was incorrect:
else {
document.querySelector("#result").innerHTML="You are Wrong in guess";
//push the current guess onto the guesses array:
guesses.push(a);
//update the div (<div id="guessArr"></div>) to hold a stringified representation
//of our array, such as ["1", "2", "3"] if the user guesses 1, then 2, then 3:
document.querySelector("#guessArr").innerHTML = JSON.stringify(guesses);
//create a p tag (<p></p>) to store our message
var p = document.createElement('p')
//add the message to that p tag:
p.innerHTML = x+1+": number turn is wrong"
//append it to the div:
document.getElementById("finalize").appendChild(p)
//add one to our guess number/count:
x += 1;
}
}
<!-- Here is the HTML file -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My gussing game</title>
<script src="index.js"></script>
</head>
<body>
<div style="width: 45%; float: left; background: gold; margin: 2px; text-align: center;">
<H1>Game Input</H1>
<hr>
<input type="number" id="inpt" placeholder="Guess the number">
<br>
<button onclick="check()">Submit</button>
<p id="result"></p>
</div>
<div style="width: 45%; float: left; background: rgb(42, 204, 177); margin: 2px; text-align: center;">
<h1>Game Result</h1>
<hr>
<div id="guessArr"></div>
<div id="finalize">
</div>
</div>
</body>
</html>

Using <label> <input> <br> in for loop

I'd like to ask on how to add label, input, and br in for loop please. I'm trying to create an application to calculate score/GPA with for loop. Basically, if I enter 4 then 4 boxes of test scores will show up for me to enter (the default value is 150) - and the maximum I can go is 5.
I'm having problem putting label, input, and br in the for loop - the code is fine and it ran, but you obviously see that I'm not using label, input, and br tags.
How may I add these in please?
For example, if I enter 3 in the number of exams, then setupInputBox() will generate three label, three input and three br elements.
I attached my codes below.
Thank you so much!
// define a function so that in js code, $ can be used to replace document.getElementById
var $ = function(id) {
return document.getElementById(id);
};
var numInputs = 1; //default setting, showing one test score input box
//define setupInputBox function to add more test score inputs boxes
var setupInputBox = function() {
$('testInputs').innerHTML = "";
$('scoreTotal').value = "";
$('scoreAvg').value = "";
$('scoreFinal').value = "";
numInputs = $('numscores').value;
numInputs = parseInt(numInputs);
// convert inputs into integer numerical value
//step-1.1: Add a condition in if() statement
//if user input for number of test scores is valid and in the range 1 to 5
if (Number.isInteger(numInputs) && numInputs >= 1 && numInputs <= 5) {
var mainDiv = document.getElementById("testInputs");
for (var i = 0; i < numInputs; i++) {
//Step-1.2.1: create new <label>, <input>, and <br> elements (use createElement() method)
var lbl = document.createElement('label');
var inp = document.createElement("input");
var br = document.createElement("br");
//Step-1.2.2: create text content node for each new <label> element ( use createTextNode() method )
lbl.append(document.createTextNode("Test-" + (i + 1)));
//Step-1.3.1: add for attribute to each new <label> element ( use setAttribute() method)
lbl.setAttribute("for", "score" + (i + 1));
//Step-1.3.2: add id, type, and value attributes to new <input> elements ( use setAttribute() method)
inp.setAttribute("id", "score" + (i + 1));
inp.setAttribute("value", "150");
inp.setAttribute("type", "number");
//Step-1.4: append each new <label>, <input>, and <br> elements to the <div> element with id=”testInputs”.
mainDiv.append(lbl, inp, br);
}
}
};
//whenever user changes selection on number of test scores to consider, setupInputBox function will be executed again
$('numscores').oninput = setupInputBox;
//define processEntries function to get user inputted test scores, do input validation, and caculate total and average points and
//determine the final letter grade. Display all results on web page.
var processEntries = function() {
$('scoreTotal').value = "";
$('scoreAvg').value = "";
$('scoreFinal').value = "";
var score = []; //define an array to hold test scores
var message = ""; //define a variable for containing and displaying error message
var totalscore = 0,
avgScore, finalScore;
var isValid = true;
for (var i = 0; i < numInputs; i++) //
{
$("score" + (i + 1)).className = "";
//step 2.1: add js code to read in each user inputted test score(s) from input test score boxes on the web page.
var test = document.getElementById("score" + (i + 1));
var testScore = parseFloat(test.value);
//step 2.2: add js code to validate each test score to make sure all inputted test scores are numerical values
//between 0 and 150 (i.e., no less than 0 and no greater than 150 points).
if (!Number.isNaN(testScore) && testScore >= 0 && testScore <= 150) {
//if a test score is valid, add that test score to the score array.
score.push(testScore);
} else {
isValid = false;
//if a test score is invalid, generate error message, and add that error messge to message string.
message += "Test-" + (i + 1) + " score input is invalid. Should be a number between 0 and 150.\n"
test.setAttribute("class", "error");
}
}
console.log(score); //print out score array in console
console.log(message); //print out message string in console
if (isValid) {
//step2.3: add js so that when all inputted test scores are valid, compute total points, average points (with zero decimal place), and
//final letter grade, and display them in the input boxes in the <div> element with id=’result’ on the web page.
for (var j = 0; j < numInputs; j++) {
totalscore += score[j];
}
totalscore = totalscore.toFixed(1);
avgScore = totalscore / numInputs;
avgScore = avgScore.toFixed(1);
var scoreTotal = document.getElementById('scoreTotal');
scoreTotal.value = totalscore.toString();
var scoreAvg = document.getElementById('scoreAvg');
scoreAvg.value = avgScore.toString();
avgScore = parseFloat(avgScore);
if (avgScore <= 150 && avgScore >= 120)
finalScore = "A";
else if (avgScore < 120 && avgScore >= 100)
finalScore = "B";
else if (avgScore < 100 && avgScore >= 80)
finalScore = "C";
else if (avgScore < 80 && avgScore >= 60)
finalScore = "D";
else if (avgScore < 60)
finalScore = "F";
var scoreFinal = document.getElementById("scoreFinal")
scoreFinal.value = finalScore
} else {
//If not all inputted test scores are valid, then create an alert box to display an error message
alert(message);
}
}; //end of processEntries function
//each time when calculate button is clicked, inputted test scores will be evaluated and
$("calculate").onclick = function() {
if (numInputs > 0 && numInputs < 6)
processEntries();
};
$("numscores").focus();
#import url(http://fonts.googleapis.com/css?family=Wellfleet);
body {
font-family: 'Wellfleet', Arial, Helvetica, sans-serif;
background-color: white;
margin: 0 auto;
width: 60%;
min-width: 600px;
border: 3px solid blue;
padding: 0 1em .5em;
}
h1 {
color: blue;
margin: .5em 0;
}
#teacher {
float: right;
margin: 0px 30px 0px 0px;
}
label {
float: left;
width: 10em;
text-align: right;
margin-bottom: .5em;
}
input {
width: 5em;
margin-left: 1em;
margin-bottom: .5em;
}
input.error {
background-color: yellow;
}
#s1 {
display: inline-block;
}
#s1 input {
vertical-align: center;
float: left;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Test Score App</title>
<link rel="stylesheet" href="score.css">
</head>
<body>
<main>
<h2>The Test Scores App</h2>
<img src="teacher.png" id="teacher" alt="teacher" width="177" height="277">
<div id="s1">
<label for="numscores">How many tests you want to consider?</label>
<input type='number' id='numscores' min='1' max='10' value='1'>
</div>
<div id="testInputs">
<label for="score1">Test-1:</label>
<input type='number' id='score1' value='150' /><br>
</div>
<div id='result'>
<label for="scoreTotal">Total Points:</label>
<input type="number" id="scoreTotal" disabled><br>
<label for="scoreAvg">Avg Grade:</label>
<input type="number" id="scoreAvg" disabled><br>
<label for="scoreFinal">Final Letter Grade:</label>
<input type="text" id="scoreFinal" disabled><br>
<label> </label>
<input type="button" id="calculate" value="Calculate">
</div>
</main>
<script src="testScoreV2.js">
</script>
</body>
</html>
Use a template literal and you can make this a lot simpler
// define a function so that in js code, $ can be used to replace document.getElementById
var $ = function(id) {
return document.getElementById(id);
};
var numInputs = 1; //default setting, showing one test score input box
//define setupInputBox function to add more test score inputs boxes
var setupInputBox = function() {
$('testInputs').innerHTML = "";
$('scoreTotal').value = "";
$('scoreAvg').value = "";
$('scoreFinal').value = "";
//string to hold our new html
let newHTML = "";
numInputs = $('numscores').value;
numInputs = parseInt(numInputs);
// convert inputs into integer numerical value
//step-1.1: Add a condition in if() statement
//if user input for number of test scores is valid and in the range 1 to 5
if (Number.isInteger(numInputs) && numInputs >= 1 && numInputs <= 5) {
var mainDiv = document.getElementById("testInputs");
for (var i = 0; i < numInputs; i++) {
//Create new html using template literal
newHTML += `<label for='score${i+1}'>Test - ${i+1}</label><input type='number' value='150' id='score${i+1}'><br>`;
}
//Update the div
mainDiv.innerHTML += newHTML;
}
};
//whenever user changes selection on number of test scores to consider, setupInputBox function will be executed again
$('numscores').oninput = setupInputBox;
//define processEntries function to get user inputted test scores, do input validation, and caculate total and average points and
//determine the final letter grade. Display all results on web page.
var processEntries = function() {
$('scoreTotal').value = "";
$('scoreAvg').value = "";
$('scoreFinal').value = "";
var score = []; //define an array to hold test scores
var message = ""; //define a variable for containing and displaying error message
var totalscore = 0,
avgScore, finalScore;
var isValid = true;
for (var i = 0; i < numInputs; i++) //
{
$("score" + (i + 1)).className = "";
//step 2.1: add js code to read in each user inputted test score(s) from input test score boxes on the web page.
var test = document.getElementById("score" + (i + 1));
var testScore = parseFloat(test.value);
//step 2.2: add js code to validate each test score to make sure all inputted test scores are numerical values
//between 0 and 150 (i.e., no less than 0 and no greater than 150 points).
if (!Number.isNaN(testScore) && testScore >= 0 && testScore <= 150) {
//if a test score is valid, add that test score to the score array.
score.push(testScore);
} else {
isValid = false;
//if a test score is invalid, generate error message, and add that error messge to message string.
message += "Test-" + (i + 1) + " score input is invalid. Should be a number between 0 and 150.\n"
test.setAttribute("class", "error");
}
}
console.log(score); //print out score array in console
console.log(message); //print out message string in console
if (isValid) {
//step2.3: add js so that when all inputted test scores are valid, compute total points, average points (with zero decimal place), and
//final letter grade, and display them in the input boxes in the <div> element with id=’result’ on the web page.
for (var j = 0; j < numInputs; j++) {
totalscore += score[j];
}
totalscore = totalscore.toFixed(1);
avgScore = totalscore / numInputs;
avgScore = avgScore.toFixed(1);
var scoreTotal = document.getElementById('scoreTotal');
scoreTotal.value = totalscore.toString();
var scoreAvg = document.getElementById('scoreAvg');
scoreAvg.value = avgScore.toString();
avgScore = parseFloat(avgScore);
if (avgScore <= 150 && avgScore >= 120)
finalScore = "A";
else if (avgScore < 120 && avgScore >= 100)
finalScore = "B";
else if (avgScore < 100 && avgScore >= 80)
finalScore = "C";
else if (avgScore < 80 && avgScore >= 60)
finalScore = "D";
else if (avgScore < 60)
finalScore = "F";
var scoreFinal = document.getElementById("scoreFinal")
scoreFinal.value = finalScore
} else {
//If not all inputted test scores are valid, then create an alert box to display an error message
alert(message);
}
}; //end of processEntries function
//each time when calculate button is clicked, inputted test scores will be evaluated and
$("calculate").onclick = function() {
if (numInputs > 0 && numInputs < 6)
processEntries();
};
$("numscores").focus();
#import url(http://fonts.googleapis.com/css?family=Wellfleet);
body {
font-family: 'Wellfleet', Arial, Helvetica, sans-serif;
background-color: white;
margin: 0 auto;
width: 60%;
min-width: 600px;
border: 3px solid blue;
padding: 0 1em .5em;
}
h1 {
color: blue;
margin: .5em 0;
}
#teacher {
float: right;
margin: 0px 30px 0px 0px;
}
label {
float: left;
width: 10em;
text-align: right;
margin-bottom: .5em;
}
input {
width: 5em;
margin-left: 1em;
margin-bottom: .5em;
}
input.error {
background-color: yellow;
}
#s1 {
display: inline-block;
}
#s1 input {
vertical-align: center;
float: left;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Test Score App</title>
<link rel="stylesheet" href="score.css">
</head>
<body>
<main>
<h2>The Test Scores App</h2>
<img src="teacher.png" id="teacher" alt="teacher" width="177" height="277">
<div id="s1">
<label for="numscores">How many tests you want to consider?</label>
<input type='number' id='numscores' min='1' max='10' value='1'>
</div>
<div id="testInputs">
<label for="score1">Test-1:</label>
<input type='number' id='score1' value='150' /><br>
</div>
<div id='result'>
<label for="scoreTotal">Total Points:</label>
<input type="number" id="scoreTotal" disabled><br>
<label for="scoreAvg">Avg Grade:</label>
<input type="number" id="scoreAvg" disabled><br>
<label for="scoreFinal">Final Letter Grade:</label>
<input type="text" id="scoreFinal" disabled><br>
<label> </label>
<input type="button" id="calculate" value="Calculate">
</div>
</main>
<script src="testScoreV2.js">
</script>
</body>
</html>

Take the values of a text input and store them into an array

My code can be found here: https://www.w3schools.com/code/tryit.asp?filename=FHC2UOT0RQX6
The program accepts an array var array=[1,0,1,0,1,1,0,0,0] and solves the pseudoternary encoding scheme. All i want to do is simple. Insead of changing the elements of the array(when i want to insert a different input), i want to use the input text and take the values from it and when i press enter or the submit button, it will solve the problem depending on the user inputs. Is that possible to take the values of the text input and make them act as an array ?
Here is the script below but it is better to see the whole code, use the link above.
<script type="text/javascript">
var array=[1,0,1,0,1,1,0,0,0]; //input here
var text="";
for(var b=0;b<array.length;b++)
{
text+=array[b];
}
document.getElementById('enc').innerHTML=text;
pseudo(array);
function pseudo(a) //function pseudo
{
var pulse = false;
var count = 0;
for(var b=0;b<array.length;b++)
if(a[b]===1)
{
count++;
document.write('<img src="http://i.imgur.com/30DU9iC.png">');
}
else if(a[b]===0)
{
count++;
pulse=!pulse; //toggles boolean value each time it finds zero
if(pulse===true) //pulse shows up
{
document.write('<img src="http://i.imgur.com/Ghtajy7.png">');
}
else{
document.write('<img class="down" src="http://i.imgur.com/uObQjTA.png">');
}
}
}
</script>
Actually you want to write your code inside a function and call the function onload and onclick respectively. Try this, http://www.w3schools.com/code/tryit.asp?filename=FALV2XZQ7V36
var array = [1, 0, 1, 0, 1, 1, 0, 0, 0]; //input here
var text = "";
function loading() {
for (var b = 0; b < array.length; b++) {
text += array[b];
}
document.getElementById('enc').innerHTML = text;
pseudo(array);
}
function pseudo(a) //function pseudo
{
var pulse = false;
var count = 0;
var output = '';
var b = 0;
for (b = 0; b < a.length; b++)
if (a[b] === 1) {
count++;
//document.write('<p class="w3-center w3-text-red">'+'Step '+count+': No line'+'<br>'+'</p>');
//document.write('<img src="http://i.imgur.com/30DU9iC.png">');
output += '<img src="http://i.imgur.com/30DU9iC.png">';
} else if (a[b] === 0) {
count++;
pulse = !pulse; //toggles boolean value each time it finds zero
if (pulse === true) //pulse shows up
{
//document.write('<p class="w3-center w3-text-red">'+'Step: '+count+' goes up'+'<br>'+'</p>');
//document.write('<img src="http://i.imgur.com/Ghtajy7.png">');
output += '<img src="http://i.imgur.com/Ghtajy7.png">';
} else {
// document.write('<p class="w3-center w3-text-red">'+'Step: '+count+' goes down'+'<br>'+'</p>');
//document.write('<img class="down" src="http://i.imgur.com/uObQjTA.png">');
output += '<img class="down" src="http://i.imgur.com/uObQjTA.png">';
}
}
document.getElementById("js").innerHTML = output;
}
function gettext() {
var inputText = document.getElementById("tf").value;
var inparray = [inputText.length];
for (i in inputText) {
inparray[i] = parseInt(inputText[i]);
}
document.getElementById('enc').innerHTML = inputText;
pseudo(inparray);
}
body {} .pad {
padding-top: 20%;
}
.inline {
display: inline;
}
.down {
margin: 0 -2 -65 -3;
}
<html>
<head>
<title>Pseudoternary Encoding</title>
<link rel="stylesheet" href="http://www.w3schools.com/lib/w3.css">
<!-- <link rel="stylesheet" href="style.css" type="text/css"/>-->
<h4>Use this input </h4>
<input type="text" id="tf"></input>
<input type="button" style="width:50px;" value="solve" onclick="gettext()" id="tf"></input>
</head>
<body onload="loading()" ;>
<h1>Illustration of pseudoternary encoding scheme </h1>
<h1 class="pad w3-center">Encode <span id="enc" class="w3-text-red"> </span></h1>
<div id="js" class="w3-center">
</div>
</body>
</html>
Note, <input> element is self-closing. <input> element should be child nodes of <body> element instead of <head> element. id of element in document should be unique. Replace duplicate "tf" id at input elements with unique values. Remove <script> element from being child node of div element. Place <script> element before closing </body> tag. Substitute concatenating .innerHTML for document.write()
Attach click event to input type="button", use String.prototype.split() with parameter "" to create an array from input type="text" .value, Array.prototype.map() with parameter Number to convert String to Number values. Assign resulting array to array variable. Set #js .innerHTML to empty string before calling function again with array as parameter.
<!DOCTYPE html>
<html>
<head>
<style>
body {}
.pad {
padding-top: 20%;
}
.inline {
display: inline;
}
.down {
margin: 0 -2 -65 -3;
}
</style>
<title>Pseudoternary Encoding</title>
<link rel="stylesheet" href="http://www.w3schools.com/lib/w3.css">
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<h4 style="margin-top:240px;position:absolute">Use this input </h4>
<h1>Illustration of pseudoternary encoding scheme </h1>
<input type="text" style="position:relative" id="tf">
<input type="button" style="position:relative;width:50px;" value="solve" id="button">
<h1 class="pad w3-center">Encode <span id="enc" class="w3-text-red"> </span></h1>
<div id="js" class="w3-center"> </div>
<script>
var array = [1, 0, 1, 0, 1, 1, 0, 0, 0]; //input here
var text = "";
var enc = document.getElementById("enc");
var button = document.getElementById("button");
var tf = document.getElementById("tf");
var center = document.getElementById("js");
for (var b = 0; b < array.length; b++) {
text += array[b];
}
enc.innerHTML = text;
pseudo(array);
function pseudo(a) {
var pulse = false;
var count = 0;
for (var b = 0; b < array.length; b++)
if (a[b] === 1) {
count++;
center.innerHTML += '<img src="http://i.imgur.com/30DU9iC.png">';
} else if (a[b] === 0) {
count++;
pulse = !pulse; //toggles boolean value each time it finds zero
if (pulse === true) //pulse shows up
{
center.innerHTML += '<img src="http://i.imgur.com/Ghtajy7.png">';
} else {
center.innerHTML += '<img class="down" src="http://i.imgur.com/uObQjTA.png">';
}
}
}
button.onclick = function() {
array = tf.value.split("").map(Number);
enc.innerHTML = array.join("");
console.log(array, enc);
center.innerHTML = "";
pseudo(array)
}
</script>
</body>
</html>

Categories

Resources