UPDATE so here is a better code for you. I cut it down to have only what's strictly necessary for you to reproduce the problem.
// change the color of the button when mousedown/up
let button = document.getElementsByClassName('button');
for(i = 0; i < button.length; i++){
button[i].onmousedown = function() {
this.style.backgroundColor = "#a3a3a3";
};
button[i].onmouseup = function() {
this.style.backgroundColor = "#808080";
};
}
let buttonLg = document.getElementsByClassName('button-lg');
for(i = 0; i < buttonLg.length; i++){
buttonLg[i].onmousedown = function() {
this.style.backgroundColor = "#a3a3a3";
};
buttonLg[i].onmouseup = function() {
this.style.backgroundColor = "#808080";
};
}
let button2 = document.getElementsByClassName('button2');
for(i = 0; i < button2.length; i++){
button2[i].onmousedown = function() {
this.style.backgroundColor = "#ffe299";
};
button2[i].onmouseup = function() {
this.style.backgroundColor = "#ffca47";
};
}
// show the numbers typed or result
let result = document.getElementById('result');
let preview = [];
let buttonAc = document.getElementById('ac');
let plusMinus = document.getElementById('plus-minus');
let plusMinus2 = document.getElementById('plus-minus2');
let buttonN7 = document.getElementById('seven');
let buttonN72 = document.getElementById('seven2');
let buttonN8 = document.getElementById('eight');
let buttonN82 = document.getElementById('eight2');
let buttonN9 = document.getElementById('nine');
let buttonN92 = document.getElementById('nine2');
// button AC erasing result and changing outlook to C when other buttons are clicked
// number 0 disapear when there is only zero and when a key is clicked
buttonAc.onclick = function () {
buttonAc.innerHTML = "AC";
preview = [];
result.innerHTML = 0;
}
// concatenation of the buttons numbers without any commas
buttonN7.onclick = function () {
document.getElementById('ac').innerHTML = "C";
buttonN7 = 7;
preview.push(buttonN7);
const a = preview.join('');
result.innerHTML = a;
}
buttonN8.onclick = function () {
document.getElementById('ac').innerHTML = "C";
buttonN8 = 8;
preview.push(buttonN8);
const a = preview.join('');
result.innerHTML = a;
}
buttonN9.onclick = function () {
document.getElementById('ac').innerHTML = "C";
buttonN9 = 9;
preview.push(buttonN9);
const a = preview.join('');
result.innerHTML = a;
}
// positive to negative value and vice versa with the plus, minus key
plusMinus.onclick = function(){
let a = preview.join('');
let b = parseInt(a, 10);
let c = b * -1;
result.innerHTML = c;
plusMinus.style.display = "none";
plusMinus2.style.display = "block";
//this code below works
//document.getElementById('nine').style.display = "none";
//that one does not work
buttonN9.style.display = "none";
buttonN92.style.display = "block";
}
plusMinus2.onclick = function(){
let a = preview.join('');
let b = parseInt(a, 10);
let c = b * -1;
result.innerHTML = b;
plusMinus2.style.display = "none";
plusMinus.style.display = "block";
}
buttonN92.onclick = function(){
result.innerHTML = 0;
preview = [];
//this code below works
//document.getElementById('nine').style.display = "block";
//that one does not work
buttonN9.style.display = "block";
buttonN92.style.display = "none";
}
h1 {
padding: 30px;
}
.result {
font-size: 80px;
border: 2px solid #000;
color: #f9f9f9;
padding-right: 20px;
background-color: #696969;
}
.row1 {
border: 2px solid #000;
}
.button,
.button2,
.button-lg {
width: 25%;
}
p {
cursor: pointer;
}
#ac,
#plus-minus,
#plus-minus2,
#percentage,
#seven,
#eight,
#nine,
#seven2,
#eight2,
#nine2 {
font-size: 40px;
background-color: #808080;
color: #f9f9f9;
height: 140px;
padding-top: 50px;
margin-bottom: 0px;
border-right: 1px solid #696969;
}
#ac,
#plus-minus,
#percentage,
#seven,
#eight,
#nine {
display: block;
}
#plus-minus2,
#seven2,
#eight2,
#nine2 {
display: none;
}
#division,
#multiplication{
font-size: 40px;
background-color: #ffca47;
color: #f9f9f9;
height: 140px;
margin-bottom: 0px;
padding-top: 50px;
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<title>Calculator</title>
</head>
<body>
<h1 class="text-center">Calculator</h1>
<div class="container">
<div class="row">
<div class="col-xl-12">
<h5 id="result" class="card-title text-right result">0</h5>
</div>
</div>
<div class="row">
<div class="col-xl-12">
<div class="card-group row1">
<p id="ac" class="card-text text-center button">AC</p>
<p id="plus-minus" class="card-text text-center button">+ | -</p>
<p id="plus-minus2" class="card-text text-center button">+ | -</p>
<p id="percentage" class="card-text text-center button">%</p>
<p id="division" class="card-text text-center button2">/</p>
</div>
</div>
</div>
<div class="row">
<div class="col-xl-12">
<div class="card-group row2">
<p id="seven" class="card-text text-center button">7</p>
<p id="seven2" class="card-text text-center button">7</p>
<p id="eight" class="card-text text-center button">8</p>
<p id="eight2" class="card-text text-center button">8</p>
<p id="nine" class="card-text text-center button">9</p>
<p id="nine2" class="card-text text-center button">9</p>
<p id="multiplication" class="card-text text-center button2">X</p>
</div>
</div>
</div>
</div>
<script type="text/javascript" src="script.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
</body>
</html>
So here is the idea: It's a calculator, so I opened my calculator from my iMac and I just checked the behavior to try to reproduce it.
What you can do:
- clicking on the number, showing them on the screen result.
- Clicking on AC make the button change to C and clear the screen result.
- Clicking on %, / and X makes nothing yet.
- Clicking on "+|-" swap the number to it's minus.
Here is what I'm trying to do. Normally, when you click the "+|-" key several time, it's going from negative to positive etc. ... and, normally if you click on a number it should go back to 0. I tried first with an external button to test and then I used the key 9 to see if it will work fine, with that code here:
document.getElementById('nine').style.display = "block"; //or none
It works perfectly! But, when I throw that code instead (I marked them up on the whole snippet to you identify them better)
buttonN9.style.display = "block"; //or none
BADABOOM, red alert on the console.
I've tried everything on every sens since hours; return my brain as much as I can; I'm still doing it. This evening, I must go somewhere with my wife. It's going to be hard to not think about it.
I will be honest with you, the calculator from the iPhone does not have the same behavior. If you fire 1,2,3 then +|- it goes -123. If you fire again 7, it goes -1237. So, maybe I mess up my brain too much, but I want to do it :)
Simply put all your code that accesses the DOM in a window.onload() handler, like this:
<script>
window.onload = function() {
let plusMinus = document.getElementById('plus-minus');
let buttonN9 = document.getElementById('nine');
// other variable initialization
plusMinus.onclick = function() {
buttonN9.style.display = "none";
// other handler code logic
}
// other event handlers
};
</script>
This way, you are sure the DOM is ready before accessing or manipulating it.
Also, from the html file in your Github repository here; you included several external scripts (including jquery) after your script. Except these scripts depend on your own script - which is not likely, you should always place your own script last after other external scripts that your code may likely depend on.
UPDATE: There are issues with firing window.onload from within the body tag. see the answer on this post. In addition to my previous answer, try putting your scripts in the header tag like this:
<head>
<!-- Place other external scripts here -->
<script src='myscript.js'></script>
</head>
So, here is the solution. As a beginner, i made first some mistakes, i was repeating the functions. I've created for each behavior one function. The main problem is i wanted to get to an index thru an array without using any loop. The loop for made the deal and now it's behaving as i want ...
The list of the buttons did not change. What you have:
- A function to handle a reset button.
- A function to handle the value of the numbers buttons
- A function to the positive/negative number
- A function to reset the positive/negative number in case you click on one number.
This is how behave the calculator that i have so i'm just trying to do the exactly same thing. Thanks a lot for your help !
function buttonResetHandler(button){
button.onclick = function (){
button.innerHTML = "AC";
preview = [];
result.innerHTML = 0;
}
}
buttonResetHandler(buttonAc);
// concatenation of the buttons numbers without any commas
function buttonNumberHandler(button, value){
button.onclick = function(){
buttonAc.innerHTML = "C";
button = value;
preview.push(button);
const a = preview.join('');
result.innerHTML = a;
}
}
buttonNumberHandler(buttonN0, 0);
buttonNumberHandler(buttonN1, 1);
buttonNumberHandler(buttonN2, 2);
buttonNumberHandler(buttonN3, 3);
buttonNumberHandler(buttonN4, 4);
buttonNumberHandler(buttonN5, 5);
buttonNumberHandler(buttonN6, 6);
buttonNumberHandler(buttonN7, 7);
buttonNumberHandler(buttonN8, 8);
buttonNumberHandler(buttonN9, 9);
// positive to negative value and vice versa with the plus, minus key
function buttonPlusMinusHandler(button1, button2, button3, button4){
button1.onclick = function(){
let a = preview.join('');
let b = parseInt(a, 10);
let c = b * -1;
result.innerHTML = c;
button1.style.display = "none";
button2.style.display = "block";
for(i = 0; i < button3.length; i++){
button3[i].style.display = "none";
}
for(i = 0; i < button4.length; i++){
button4[i].style.display = "block";
}
if(result.innerHTML == c){
button2.onclick = function(){
result.innerHTML = b;
button2.style.display = "none";
button1.style.display = "block";
}
}
}
}
buttonPlusMinusHandler(plusMinus, plusMinus2, allButtonsN, allButtonsN2);
function buttonNumberResetPlusMinus(button, button2){
for(i = 0; i < button.length; i++){
button[i].onclick = function(){
preview = [];
result.innerHTML = 0;
for(i = 0; i < button2.length; i++){
button[i].style.display = "none";
button2[i].style.display = "block";
}
}
}
}
buttonNumberResetPlusMinus(allButtonsN2, allButtonsN);
Related
I'm trying to make a very basic expense tracker by building off the foundation of a todo app with vanilla Javascript. I'm having trouble isolating the value of all three input bars and getting them to display on the page. At the moment I'm getting 3 [objectHTMLInputElement] and undefined. I'd just like to know if I'm on the right track or if there's an easier way to isolate multiple input values and get them to display on the page. If somebody could point me in the right direction that'd be awesome. Thanks!
let addButton = document.getElementById('add-btn');
addButton.addEventListener('click', add);
let inputName = document.getElementById('input-name');
let inputDate = document.getElementById('input-date');
let inputAmount = document.getElementById('input-amount');
let inputAll = document.querySelectorAll('.input-all');
let expenses = [
]
function add() {
let inputs = inputAll.value;
if (inputs == '') {
return true;
}
expenses.push(inputs);
displayExpenses();
}
function remove() {
}
function displayExpenses() {
let expensesUl = document.getElementById('expenses-ul');
expensesUl.innerHTML = `${inputName}${inputDate}${inputAmount}`;
for (var i = 0; i < expenses.length; i++) {
let expensesLi = document.createElement('li');
expensesLi.innerHTML = expenses[i];
expensesUl.appendChild(expensesLi);
}
}
* {
padding: 0;
box-sizing: border-box;
}
.headings {
text-align: center;
}
.headings h1 {
font-size: 3rem;
font-family: 'Courier New', Courier, monospace;
}
.headings h2 {
margin-top: -20px;
}
form {
text-align: center;
}
#input-name {
width: 50%;
}
#input-date {
width: 18%;
margin-right: 160px;
}
#input-amount {
width: 18%;
margin-left: 18px;
}
#add-btn {
margin-top: 50px;
margin-left: 800px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>Expense Tracker</title>
</head>
<body>
<div class="headings">
<h1>Expense Tracker</h1>
<h2>Add A New Item</h2>
</div>
<form>
<label>Name:</label>
<input class="input-all" id="input-name">
<br>
<br>
<label>Date:</label>
<input class="input-all" id="input-date">
<label>Amount:</label>
<input class="input-all" id="input-amount">
</form>
<button id="add-btn">Add Expense</button>
<ul id="expenses-ul"></ul>
<script src="main.js"></script>
</body>
</html>
Try this
const btn = document.getElementById('btn');
btn.addEventListener('click', function (event) {
const form = document.getElementById('form');
const output = document.getElementById('output');
const data = Object.fromEntries(new FormData(form).entries());
output.innerHTML = JSON.stringify(data, undefined, 2);
});
.wrap{
display: flex;
}
#output{
margin-left:50px;
border-width:3px;
border-style:dashed;
border-color:#FFAC55;
padding:5px;
min-width: 150px;
min-height: 80px;
}
<div class="wrap">
<div>
<form id="form">
<label for="name">Name:</label><br>
<input type="text" id="name" name="name"><br>
<label for="date">Date:</label><br>
<input type="text" id="role" name="role"> <br>
<label for="lname">Amount:</label><br>
<input type="text" id="amount" name="amount"><br><br>
<input id="btn" type="button" value="Print all value">
</form>
</div>
<div>
<pre id="output">
</pre>
</div>
</div>
When using document.querySelectorAll it's return a [NodeList] that consists of all selected elements on the other side there's also document.getElementsByClassName that return [HTMLCollection] - whatever you used you need to loop through to get the value of every selected input
When you passed [HTMLInputElement] as innerHTML of expensesUl it's will return the element object name not the value of this element because you are not selected any property of this object so you can't set an object as innerHTML of html element
if you want the right way of this part it's will be like that
let inputName = document.getElementById('input-name');
let inputDate = document.getElementById('input-date');
let inputAmount = document.getElementById('input-amount');
let expensesUl = document.getElementById('expenses-ul');
//this will give you empty string because they aren't get a value yet
expensesUl.innerHTML = `name = ${inputName.value}, date = ${inputDate.value}, amoute = ${inputAmount.value}`;
but now because we are selected all elements we are not need to select every input one by one anymore we will make a loop so we will loop through inputAll var to get the value of [HTMLInputElement] object
let addButton = document.getElementById('add-btn');
addButton.addEventListener('click', add);
function add() {
let inputAll = document.querySelectorAll('.input-all');
for(var i of inputAll) {
if (i.value == '') {
return "Sorry you need to fill all inputs"
}
}
displayExpenses(inputAll);
}
function displayExpenses(elements) {
let expensesUl = document.getElementById('expenses-ul');
for (var i = 0; i < elements.length; i++) {
let expensesLi = document.createElement('li');
expensesLi.innerHTML = elements[i].value
expensesUl.appendChild(expensesLi);
}
}
at the example above i removed expenses array but if you want to use it to take the value of the inputs you can make it like that
let addButton = document.getElementById('add-btn');
addButton.addEventListener('click', add);
function add() {
let inputAll = document.querySelectorAll('.input-all');
let expenses = []
for(var i of inputAll) {
if (i.value == '') {
return "Sorry you need to fill all inputs"
}
expenses.push(i.value)
}
displayExpenses(expenses);
}
function displayExpenses(values) {
let expensesUl = document.getElementById('expenses-ul');
for (var i = 0; i < values.length; i++) {
let expensesLi = document.createElement('li');
expensesLi.innerHTML = values[i]
expensesUl.appendChild(expensesLi);
}
}
the whole code should to be like that
let addButton = document.getElementById('add-btn');
addButton.addEventListener('click', add);
let inputName = document.getElementById('input-name');
let inputDate = document.getElementById('input-date');
let inputAmount = document.getElementById('input-amount');
let inputAll = document.querySelectorAll('.input-all');
let expenses = []
function add() {
for(var i of inputAll) {
if (i.value == '') {
return true
}
expenses.push(i.value)
}
displayExpenses();
}
function displayExpenses() {
let expensesUl = document.getElementById('expenses-ul');
expensesUl.innerHTML = `${inputName.value}, ${inputDate.value}, ${inputAmount.value}`;
for (var i = 0; i < expenses.length; i++) {
let expensesLi = document.createElement('li');
expensesLi.innerHTML = expenses[i];
expensesUl.appendChild(expensesLi);
}
}
about document.getElementsByClassName, document.querySelectorAll one deferant is that you can use array methods like forEach() with document.querySelectorAll while you can't do that with document.getElementsByClassName
I looked at a few examples on how to make a typewriter effect but my solution doesn't seem to work.I have three sentences that I want to loop forever and have them typed letter by letter to get that typewriter effect. Here is my code:
<html>
<head>
<meta charset="utf-8">
<title>Кухнята на Дани</title>
<link rel="stylesheet" href="css.css">
<script type="text/javascript" src="https://code.jquery.com/jquery-3.4.1.js"></script> <!--required for the next script-->
<!--some other javascript that requires the JQuery code above-->
<script type="text/javascript">
function typeWriter(){
var flag=0;
while(flag=0)
{
var s1 = "sentence1";
var s2 = "sentence2";
var s3 = "sentence3";
var s = "";
var i = 0;
document.getElementById("sub-element").innerHTML=s;
for(i=0; i<s1.length; i++)
{
s=s1.charAt(i);
document.getElementById("sub-element").innerHTML = document.getElementById("sub-element").innerHTML+s;
setTimeout(typeWriter, 50);
}
s="";
document.getElementById("sub-element").innerHTML=s;
for(i=0; i<s2.length;i++)
{
s=s2.charAt(i);
document.getElementById("sub-element").innerHTML = document.getElementById("sub-element").innerHTML+s;
setTimeout(typeWriter, 50);
}
s="";
document.getElementById("sub-element").innerHTML=s;
for(i=0; i<s3.length;i++)
{
s=s3.charAt(i);
document.getElementById("sub-element").innerHTML = document.getElementById("sub-element").innerHTML+s;
setTimeout(typeWriter, 50);
}
s="";
}
}
</script>
</head>
<body onload = "typeWriter()">
<header>
<!--header and navigation stuff here-->
</header>
<section id="home">
<div class="container">
<h1>Кухнята на Дани</h1>
<p id="sub-element"></p> <!--the text will appear in this paragraph-->
</div>
</section>
</body>
</html>
Due to some reason, the Javascript code won't work.
Excuse me for my code. I know it's too long but I decided to include everything that might be important.
You are using a while loop, meaning that even though you are appending one letter at a time it happens too fast (and in the same render frame) and thus you dont see the type effect.
You need to execute the function on some time interval, for example
setInterval(appendLetter, 200)
Which will execute appendLetter function every 200 ms and there you can have your chars append logic.
const text = "some text to loop"
let charIndex = 0;
function appendLetter() {
document.getElementById("aaa").innerHTML = text.substr(0, charIndex)
charIndex++;
if(charIndex > text.length) charIndex = 0;
}
setInterval(appendLetter, 250);
Try this
<section id="home">
<div class="container">
<h1>Кухнята на Дани</h1>
<p id="newmsg"></p> <!--the text will appear in this paragraph-->
</div>
</section>
Javascript code
var im = 0, ij=0;
var txtarray = ['sentence1', 'sentence2', 'sentence3'];
var speed = 100;
function typeWriter() {
if (im < txtarray[ij].length) {
document.getElementById("newmsg").innerHTML += txtarray[ij].charAt(im);
im++;
setTimeout(typeWriter, speed);
}
else{
setTimeout(repeatt, 1000);
}
}
typeWriter();
function repeatt() {
document.getElementById("newmsg").innerHTML = "";
im=0;
if(ij < txtarray.length-1){
ij++;
}
else{
ij = 0;
}
typeWriter();
}
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>
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>
I am trying to learn javascript by following this exercise from MDN website Learn JavaScript
here is my final code for the game.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Number guessing game</title>
<style>
html {
font-family: sans-serif;
}
body {
width: 50%;
max-width: 800px;
min-width: 480px;
margin: 0 auto;
}
.lastResult {
color: white;
padding: 3px;
}
</style>
</head>
<body>
<h1>Number guessing game</h1>
<p>We have selected a random number between 1 and 100. See if you can guess it in 10 turns or less. We'll tell you if your guess was too high or too low.</p>
<div class="form">
<label for="guessField">Enter a guess:</label>
<input type="text" id="guessField" class="guessField" autofocus>
<input type="submit" value="Submit guess" class="guessSubmit">
</div>
<div class="resultParas">
<p class="guesses"></p>
<p class="lastResult"></p>
<p class="lowOrHi"></p>
</div>
</body>
<script>
// Your JavaScript goes here
var randomNumber = Math.floor(Math.random() * 100) + 1;
var guesses = document.querySelector(".guesses");
var lastResult = document.querySelector(".lastResult");
var lowOrHi = document.querySelector(".lowOrHi");
var guessField = document.querySelector(".guessField");
var guessSubmit = document.querySelector(".guessSubmit");
var test; //used for creating new reset button
var count = 1; // counter for counting user input
function checkGuess() {
//alert('checkGuess is called');
var value = Number(guessField.value);
if (count === 1) {
guesses.textContent = "Previous guesses :"
}
guesses.textContent += value + ' ';
if (value === randomNumber) {
lastResult.textContent = "congratulation u successfully guessed the number";
lastResult.style.backgroundColor = "green";
lowOrHi.textContent = "";
left = 1;
setGameOver();
} else if (count === 10) {
lastResult.textContent = "game over"
lastResult.style.backgroundColor = "red";
left = 1;
setGameOver();
} else {
lastResult.textContent = "WRONG";
lastResult.style.backgroundColor = "red";
if (value < randomNumber) {
lowOrHi.textContent = "too low";
} else {
lowOrHi.textContent = "too high";
}
}
count++;
guessField.value = '';
}
guessSubmit.addEventListener("click", checkGuess);
function setGameOver() {
guessField.disabled = true;
guessSubmit.disabled = true;
test = document.createElement('button');
test.textContent = "restart game";
document.body.appendChild(test);
test.addEventListener('click', resetGame);
}
function resetGame() {
count = 1;
var resetParas = document.querySelectorAll('.resultParas');
for (var i = 0; i < resetParas.length; i++) {
resetParas[i].textContent = '';
}
guessField.disabled = false;
guessSubmit.disabled = false;
guessField.value = '';
lastResult.style.backgroundColor = 'white';
randomNumber = Math.floor(Math.random() * 100) + 1;
test.parentNode.removeChild(test);
}
</script>
</html>
But when i try to run the game and use the reset game button to restart the game then i am not able to manipulate guesses,lastResult and lowOrHi elements using textContent and backgroundColor properties.
Your blanking out everything inside .resultParas.. And this will include all you <p> tags. IOW: after doing that they have disappeared from the DOM, you can see this say in chrome inspector that .resultPara's after clicking reset game is now blank, and all your p tags have gone.
I think what you really want to do, is blank out the children (the p tags)..
You don't need querySelectorAll either, as in your case there is only the one.
var resetParas = document.querySelector('.resultParas');
for(var i = 0 ; i < resetParas.children.length ; i++) {
resetParas.children[i].textContent = '';
}