function myFunction() {
var x = Math.floor((Math.random() * 10) + 1);
document.getElementById("demoX").innerHTML = x;
var y = Math.floor((Math.random() * 10) + 1);
document.getElementById("demoY").innerHTML = y;
document.getElementById("demoP").innerHTML = " + ";
document.getElementById("equal").innerHTML = " = ";
document.getElementById("input").innerHTML = "<input id=>";
document.getElementById("check").innerHTML = "<button>Check</button>";
}
function myBunction() {
myFunction();
var b, text;
// Get the value of the input field with id="numb"
b = document.getElementById("input").value;
var D = document.getElementById("demoX").value;
var E = document.getElementById("demoY").value;
// If x is Not a Number or less than one or greater than 10
if (b == E + D) {
text = "Input is ok";
} else {
text = "Input not valid";
}
document.getElementById("demo").innerHTML = text;
}
<p>Click the button to display a random number between 1 and 10.</p>
<button onclick="myFunction()">Try it</button>
<br> <br>
<span id="demoX"></span>
<span id="demoP"></span>
<span id="demoY"></span>
<span id=equal></span>
<span id=input></span>
<span onclick="myBunction()" id=check></span>
<p id="demo"></p>
The first function throws two random numbers and the second one should check if the input form person is correct but "document.getElementById("demoX").value" returns nothing ... I was trying check values with console.log but it returns like nothing is define.
I was just trying to merge two functions from w3schools but it took me so much time. :/
Your problem is four-fold. One:
document.getElementById("demoX").value
does not return anything. A <span> element has no value. It has an innerHTML, just what you used to set it.
Two:
if (b == E + D) {
E and D will be strings. The result of adding two strings is a combined string.
"4" + "3" is not "7", it is "43".
You want to convert them to numbers first. Among other things, an unary + can do that. Try:
b = +b;
D = +D;
E = +E;
if (b == E + D) {
Three: You want to reset the form after you read out all values, not before.
Four: What's all that business creating all those fixed input fields and buttons dynamically via innerHTML anyway? Just put them into the HTML directly and let them sit there.
So...
function reset() {
var x = Math.floor((Math.random() * 10) + 1);
document.getElementById("demoX").innerHTML = x;
var y = Math.floor((Math.random() * 10) + 1);
document.getElementById("demoY").innerHTML = y;
document.getElementById("input").value = "";
document.getElementById("demoP").innerHTML = " + ";
document.getElementById("equal").innerHTML = " = ";
}
function check() {
var b, D, E, text;
// Get the value of the input field with id="numb"
b = +document.getElementById("input").value;
D = +document.getElementById("demoX").innerHTML;
E = +document.getElementById("demoY").innerHTML;
if (b == E + D) {
text = "Input is ok";
} else {
text = "Input not valid";
}
document.getElementById("demo").innerHTML = text;
reset();
}
reset();
<p>Click the button to display a random number between 1 and 10.</p>
<span id="demoX"></span>
<span id="demoP"></span>
<span id="demoY"></span>
<span id="equal"></span>
<input id="input">
<button onclick="check()">Check</button>
<p id="demo"></p>
Solved and nicer code.
Test
<script>
//=====|Generate the problem|=====//
function myGenerator() {
var x = Math.floor((Math.random() * 100) + 1);
document.getElementById("demoX").innerHTML = x;
var y = Math.floor((Math.random() * 100) + 1);
document.getElementById("demoY").innerHTML = y;
document.getElementById("demoP").innerHTML = " + ";
document.getElementById("equal").innerHTML = " = ";
document.getElementById("numbs").innerHTML = "<input id=numb>";
document.getElementById("check").innerHTML = "<button>Check</button>";
}
//=====|Check the given solution|=====//
function myChecker() {
var a, text;
a = document.getElementById("numb").value;
var b = parseFloat(document.getElementById("demoX").textContent);
var c = parseFloat(document.getElementById("demoY").textContent);
//=====|Simple if|=====//
if (a == b + c) {
alert("Congratulation");
text = "Right";
} else {
alert("Maybe next time");
text = "Wrong";
}
document.getElementById("demo").innerHTML = text;
//=====|Just for control|=====//
console.log(a);
console.log(b);
console.log(c);
}
</script>
<h1>Click to start</h1>
<button onclick="myGenerator()">Try it</button>
<br>
<br>
<!--=====|Hidden Stuff|=====//-->
<span id="demoX"></span>
<span id="demoP"></span>
<span id="demoY"></span>
<span id="equal"></span>
<span onclick="myChecker()" id=check></span>
<span id="numbs"></span>
<!--=====|Response|=====//-->
<p id="demo">
Related
I have an answer posted on this website. If I copy the code in the text field it does not work. However, if I paste the code into a word document and copy it back in, it works. I tried in notepad and google docs and it didn't work, but for some reason, word fixes it. Any idea why?
https://learningmathwithcoding.weebly.com/project-22-range-of-four-dice.html
<div>
<div>
<textarea id="box" rows="10" placeholder="Enter Your Code Here:" cols="65"></textarea>
<textarea id="box2" rows="10" cols="65" placeholder="Results Shown Here"></textarea>
<br>
<button style="width: 2cm;height: 1cm;" id="execute">Execute</button>
<canvas id="canvas" height="85" width="500">
<script>
document.getElementById('execute').onclick = function()
{
r = randomInt(0,5);
proportion = 0;
var truth = 0;
for (let trial = 1; trial <= 100000; trial++)
{
var a = randomInt(1,6);
var b = randomInt(1,6);
var c = randomInt(1,6);
var d = randomInt(1,6);
var high = a; if (b>high) high = b; if (c > high) high = c; if (d > high) high = d;
var low = a; if (b<low) low= b; if (c < low) low= c; if (d < low) low= d;
var ran = high - low;
if (ran ==r) truth++;
}
truth = truth/100000;
try{
eval(document.getElementById('box').value);
if(abs(proportion-truth)< .006)
{
document.getElementById('box2').value = "You got it: The probability that the range of four dice is " + r + " = " + proportion;
}
else
document.getElementById('box2').value = "Nope: The probability that the range of four dice is " + r + " does not equal " + proportion;
}
catch (error) {document.getElementById('box2').value = "Syntax Error";}
}
const canvas = document.querySelector('#canvas');
var r = randomInt(0,5);
var proportion;
function isClose(x,y) {return Math.abs(x-y)<.1;}
function random() {return Math.random();}
function randomInt(low, up) {var dif = up-low+1; return Math.floor(Math.random()*dif+low);}
function pow(x,y){return Math.pow(x,y);}
function abs(x) {return Math.abs(x);}
function sqrt(x) {return Math.sqrt(x);}
</script>
</div>
I was expecting to be able to copy the code in the text box it work.
You have a zero-width space (U+200B) character at the end which causes the syntax error
Clicking backspace at the end of the code fixes the error
Seems like word removes characters like that
So I have this script that get 2 prices, and then finds the sum of it, and then finds a percentage of the sum depending on what state you choose, and then it adds the percentage. This script worked kind of fine without the if..else statement, but now that I added it, it won't work. Please help. Script:
<!DOCTYPE html>
<html>
<head>
<title>Test!!!!!</title>
<style>
</style>
</head>
<body>
<h2> Price checker </h2>
<input id = "x" type = "number" placeholder = "Price 1" >
<br><br><br>
<input id = "y" type = "number" placeholder = "Price 2" >
<br><br><br>
<select id="s">
<option value="NJ">NJ</option>
<option value="NY">NY</option>
<option value="PA">PA</option>
<option value="FL">FL</option>
</select>
<br><br><br>
<button onclick = "theFunction()">Calculate price</button>
<p id = "d"></p>
<script>
function theFunction() {
var x = document.getElementById("x").value
var y = document.getElementById("y").value
var z = +x + +y
var v = document.getElementById("s").value
var percentToGet;
var percent;
var final;
if v == "NJ" {
var percentToGet = 6.625;
var percent = (percentToGet / 100) * z;
var final = +percent + +z
} else if v == "NY" {
var percentToGet = 4;
var percent = (percentToGet / 100) * z;
var final = +percent + +z
}else if v == "PA" {
var percentToGet = 2;
var percent = (percentToGet / 100) * z;
var final = +percent + +z
} else if v == "FL" {
var percentToGet = 6;
var percent = (percentToGet / 100) * z;
var final = +percent + +z
}
document.getElementById("d").innerHTML = z + " " + final
}
</script>
</body>
</html>
Your if statement in the script tag ,is javascript code which is not having the parentheses.
It will be => if (v == "NJ") { }
Refer this MDN Web Docs to learn more if...else
Is there a function that splits the the given string into 2 evenly and place half of each to different textboxes?
I have tried var.split and var.slice
<script>
function display()
{
var myStr = document.getElementbyId("reqnum").value;
var strArray = myStr.split(" ");
// Display array values on page
for(var i = 0; i < strArray.length; i++){
document.write("<p>" + strArray[i] + "</p>");
}
}
the expected should split the no. evenly and would display an error if the numbers are odd.
You can check the length of your input string. If it is odd then display an error.
<input type="text" id="reqnum" >
<input type="button" value="Display" onclick="display()">
<script>
function display()
{
var myStr = document.getElementById("reqnum").value;
if( !myStr || myStr.length % 2 == 1){
document.write("<p>Invalid input</p>");
}else{
var a = parseInt(myStr.substring(0, myStr.length/2));
var b = parseInt(myStr.substring(myStr.length/2, myStr.length));
document.write("<p>" + a + "</p>");
document.write("<p>" + b + "</p>");
document.write("<p> Result after multiplication : " + (a*b) + "</p>");
}
}
</script>
you can convert the numbers to string and then you can do the following.
var num = "1234567890"
var num1
var num2
if (num.length % 2 == 0) {
num1 = num.slice(0, (num.length / 2))
num2 = num.slice((num.length / 2))
} else {
console.log("Number contains odd number of digits")
}
console.log("Num1 " + num1 + " and Num2 " + num2)
use the Slice method, documentation is here.
For your slicing in half:
let half1, half2;
if( myStr.length % 2 == 0 ){
half1 = myStr.slice(0, (myStr.length / 2));
half2 = myStr.slice( (myStr.length / 2), myStr.length );
} else {
// error code
}
function splitToEqual(num){
num = num.toString()
return [num.substring(0, num.length / 2), num.substring(num.length / 2, num.length)]
}
console.log(splitToEqual(1234567890))
Have you tried using slice and length String methods?
Ie.
const string = '1234567890';
const length = string.length;
const res1 = string.slice(0,length/2);
const res2 = string.slice(length/2);
console.log(res1,res2);
Based on your request, I created the following piece of code :-)
Hope it helps.
var inputBox, warning, fBox, sBox;
function inputBoxChanged(e) {
var text = e.currentTarget.value;
if (text.length % 2 != 0) {
warning.innerText = "Value needs to be even sized";
fBox.value = "";
sBox.value = "";
} else {
warning.innerText = "";
var splitPos = text.length / 2;
fBox.value = text.slice(0, splitPos);
sBox.value = text.slice(splitPos, text.length);
}
}
document.addEventListener("DOMContentLoaded", function (e) {
inputBox = document.getElementById("input");
warning = document.getElementById("warning");
fBox = document.getElementById("first");
sBox = document.getElementById("second");
inputBox.addEventListener("change", inputBoxChanged);
});
<html>
<body>
<input id="input" type="text"/>
<span id="warning"></span>
<hr/>
<input id="first" type="text" readonly/>
<input id="second" type="text"readonly/>
</body>
</html>
Use substring() function as
var substring=string.substring(strating_index,end_index);
index will start from 0
var str="1234567890"
var substr=str.substring(0,str.length/2);
var substr2=str.substring(strlength/2,strlength);
$("#ID1").val(substr);
$('#ID2').val(substr2);
I've been working on my own project for a little bit, and I'm currently working on adding another button in. Now I've set it up pretty similar to the other ones, but it isn't working when I press it. For my code, the firstx2, secondx2, and first building buttons all work fine, But when you try and click on the second building button, it doesn't do anything. I probably made a small typo or missed a line, but I can't seem to find it anywhere. To get to the second building button, you have to have already clicked on both multipliers and the first building. Thanks for your help!
<!DOCTYPE html>
<html>
<body>
<p>Click to get started!</p>
<button onclick="addPoints()">Add points</button>
<button id="btn_multiply" onclick="firstx2()" style="display:none;">x2 Multiplier. Cost: 100</button>
<button id="firstbuild" onclick="build1()" style="display:none;">Building 1. Cost x</button>
<button id="multiply2" onclick="secondx2()" style="display:none;">x2 Multiplier. Cost: 1000</button>
<button id="secondbuild" onlcick="build2()" style="display:none;">Building 2. Cost x</button>
<script>
var points = 10099;
var pointMulti = 1;
var buyupgrade = 0;
var b1cost = 200;
var b1count = 0;
var b2cost = 1000;
var b2count = 0;
var currentpoints = setInterval(pointupdate, 500);
function addPoints() {
points += pointMulti;
var pointsArea = document.getElementById("pointdisplay");
pointsArea.innerHTML = "You have " + Math.round(points) + " points!";
if(points >= 100 && buyupgrade == 0) {
var multiply_button = document.getElementById("btn_multiply");
multiply_button.style.display = "inline";
}
}
function firstx2() {
if (buyupgrade == 0) {
pointMulti *= 2;
buyupgrade++;
points -= 100;
var multiplierArea = document.getElementById("multidisplay");
multiplierArea.innerHTML = "Your multiplier is: " + pointMulti;
var multiply_button = document.getElementById("btn_multiply");
multiply_button.style.display = "none";
if (buyupgrade == 1) {
var firstbuild = document.getElementById("firstbuild");
firstbuild.style.display = "inline";
firstbuild.innerText = "Building 1. Cost " + b1cost;
var show2ndx2 = document.getElementById("secondx2");
multiply2.style.display = "inline";
}
}
}
function pointupdate() {
document.getElementById("pointdisplay").innerHTML = "You have " + Math.round(points) + " points!";
}
function build1() {
if (points >= b1cost) {
points -= b1cost;
b1count++;
b1cost *= 1.10;
document.getElementById("b1").innerHTML = "You have " + b1count + " of building 1!"
firstbuild.innerText = "Building 1. Cost " + Math.round(b1cost);
var build1add = setInterval(build1points, 1000);
var secondbuild = document.getElementById("secondbuild");
secondbuild.style.display = "inline";
secondbuild.innerText = "Building 2. Cost " + b2cost;
}
}
function build2() {
if (points >= b2cost) {
points -= b2cost;
b2count++;
b2cost *= 1.10;
document.getElementById("b2").innerHTML = "You have " + b2count + " of building 2!"
secondbuild.innerText = "Building 2. Cost " + Math.round(b2cost);
var build2add = setInterval(build2points, 1000);
}
}
function build1points() {
points += 1;
}
function build2points() {
points += 4;
}
function secondx2() {
if (buyupgrade == 1 && points >= 1000) {
pointMulti *= 2;
points -= 1000;
document.getElementById("multidisplay").innerHTML = "Your multiplier is: " + pointMulti;
multiply2.style.display = "none";
}
}
</script>
<p id="pointdisplay"></p>
<p id="multidisplay"></p>
<p id="b1"></p>
<p id="b2"></p>
</body>
</html>
it should be onclick not onlcick in <button id="secondbuild" onlcick="build2()" style="display:none;">Building 2. Cost x</button>
<!DOCTYPE html>
<html>
<body>
<p>Click to get started!</p>
<button onclick="addPoints()">Add points</button>
<button id="btn_multiply" onclick="firstx2()" style="display:none;">x2 Multiplier. Cost: 100</button>
<button id="firstbuild" onclick="build1()" style="display:none;">Building 1. Cost x</button>
<button id="multiply2" onclick="secondx2()" style="display:none;">x2 Multiplier. Cost: 1000</button>
<button id="secondbuild" onclick="build2()" style="display:none;">Building 2. Cost x</button>
<script>
var points = 10099;
var pointMulti = 1;
var buyupgrade = 0;
var b1cost = 200;
var b1count = 0;
var b2cost = 1000;
var b2count = 0;
var currentpoints = setInterval(pointupdate, 500);
function addPoints() {
points += pointMulti;
var pointsArea = document.getElementById("pointdisplay");
pointsArea.innerHTML = "You have " + Math.round(points) + " points!";
if(points >= 100 && buyupgrade == 0) {
var multiply_button = document.getElementById("btn_multiply");
multiply_button.style.display = "inline";
}
}
function firstx2() {
if (buyupgrade == 0) {
pointMulti *= 2;
buyupgrade++;
points -= 100;
var multiplierArea = document.getElementById("multidisplay");
multiplierArea.innerHTML = "Your multiplier is: " + pointMulti;
var multiply_button = document.getElementById("btn_multiply");
multiply_button.style.display = "none";
if (buyupgrade == 1) {
var firstbuild = document.getElementById("firstbuild");
firstbuild.style.display = "inline";
firstbuild.innerText = "Building 1. Cost " + b1cost;
var show2ndx2 = document.getElementById("secondx2");
multiply2.style.display = "inline";
}
}
}
function pointupdate() {
document.getElementById("pointdisplay").innerHTML = "You have " + Math.round(points) + " points!";
}
function build1() {
if (points >= b1cost) {
points -= b1cost;
b1count++;
b1cost *= 1.10;
document.getElementById("b1").innerHTML = "You have " + b1count + " of building 1!"
firstbuild.innerText = "Building 1. Cost " + Math.round(b1cost);
var build1add = setInterval(build1points, 1000);
var secondbuild = document.getElementById("secondbuild");
secondbuild.style.display = "inline";
secondbuild.innerText = "Building 2. Cost " + b2cost;
}
}
function build2() {
if (points >= b2cost) {
points -= b2cost;
b2count++;
b2cost *= 1.10;
document.getElementById("b2").innerHTML = "You have " + b2count + " of building 2!"
secondbuild.innerText = "Building 2. Cost " + Math.round(b2cost);
var build2add = setInterval(build2points, 1000);
}
}
function build1points() {
points += 1;
}
function build2points() {
points += 4;
}
function secondx2() {
if (buyupgrade == 1 && points >= 1000) {
pointMulti *= 2;
points -= 1000;
document.getElementById("multidisplay").innerHTML = "Your multiplier is: " + pointMulti;
multiply2.style.display = "none";
}
}
</script>
<p id="pointdisplay"></p>
<p id="multidisplay"></p>
<p id="b1"></p>
<p id="b2"></p>
</body>
</html>
I think you should check your button(secondbuild)
the keyword onclick is wrong
Spelling Mistake. onclick not oncilck.
<button id="secondbuild" onlcick="build2()" style="display:none;">Building 2. Cost x</button> <script>
Basically, I'm making a simple javascript/html webpage game where you guess a number and you have three chances to guess correctly. I'm having a problem displaying the number of attempts a player has left (It gets stuck at three). The color change that is supposed to occur also doesn't happen.
It also doesn't reset the page's display after a refresh (it takes 5 playthroughs of the game to get it to reset).
Maybe my for loop/if statement is screwy?
Here's my code.
var guesses = 3;
var random = Math.floor((Math.random() * 10) + 1);
//start the guessing
handleGuess(prompt("Pick a number to win the game!"));
function handleGuess(choice) {
guesses--; //subtract one guess
if (guesses > 0) {
if (choice != random) {
document.body.style.backgroundColor = "#CC0000";
var x = "";
x = x + "You have " + guesses + " chances left" + "<br>";
document.getElementById("demo").innerHTML = x;
} else {
var x = "";
x = x + "You win!" + "<br>";
document.getElementById("demo").innerHTML = x;
document.body.style.backgroundColor = "#009000";
//return false;
}
} else {
//running out of turns
var x = "";
x = x + "Game Over!" + "<br>";
document.getElementById("demo").innerHTML = x;
document.body.style.backgroundColor = "#FF0000";
//return false;
}
}
The prompt is a blocking event, so you don't see the page update until after the prompts... try the example below, where setTimeout is used to allow a delay...
var guesses = 3;
var random = Math.floor((Math.random() * 10) + 1);
//start the guessing
handleGuess(prompt("Pick a number to win the game!"));
function handleGuess(choice) {
guesses--; //subtract one guess
if (guesses > 0) {
if (choice != random) {
document.body.style.backgroundColor = "#CC0000";
var x = "";
x = x + "You have " + guesses + " chances left" + "<br>";
document.getElementById("demo").innerHTML = x;
setTimeout(function() {
handleGuess(prompt("Try again!"));
},1000);//wait 1 second
} else {
var x = "";
x = x + "You win!" + "<br>";
document.getElementById("demo").innerHTML = x;
document.body.style.backgroundColor = "#009000";
//return false;
}
} else {
//running out of turns
var x = "";
x = x + "Game Over!" + "<br>";
document.getElementById("demo").innerHTML = x;
document.body.style.backgroundColor = "#FF0000";
//return false;
}
}
<h1 id="demo">You have 3 chances to guess the correct number.</h1>
<br>
Attention. This is a fully workable example, and definitely an "overkill demo" for your "blocking" request.
I've removed the prompt calls with new inputs, and created 2 buttons for the game. One that calls the Start Game, and a second for the "in game try attemps".
I'm assuming you are still learning so this example might be helpful for you,by showing the advantages of separating your code into different elements, based on what they are doing, and also making it easier for you to "upgrade" the features of your game.
I could replace a lot more repeated code to make it look better, but that would not make it so familiar anymore to you.
/*function ChangeDif(Difficulty) {
var i = ""
if (Difficulty == 'easy'){
i = 10;
}
if (Difficulty == 'medium') {
i = 5;
}
if (Difficulty == 'hard') {
i = 3;
}
}
*/
var random = 0;
var start_chances = 3;
var start_attemps = 0;
var x = "";
function startgame() {
document.getElementById("start").hidden = true;
document.getElementById("number").hidden = false;
document.getElementById("again").hidden = false;
document.getElementById("demo").innerHTML = "Pick a number to win the game!";
random = Math.floor((Math.random() * 10) + 1);
//Cheat to see the random number, and make sure the game is working fine
//document.getElementById("cheater").innerHTML= random;
max_chances = start_chances;
step();
}
function lostAchance() {
max_chances--;
if (max_chances > 0) {
step();
} else {
loser();
}
}
function loser() {
//running out of turns
x = "Game Over!" + "<br>";
document.getElementById("demo").innerHTML = x;
document.body.style.backgroundColor = "#FF0000";
endGame();
}
function step() {
var choice = parseInt(document.getElementById("number").value);
if (choice !== random) {
document.body.style.backgroundColor = "#CC0000";
x = "You have " + max_chances + " chances left" + "<br>";
document.getElementById("demo").innerHTML = x;
document.getElementById("start").hidden = true;
} else {
//win
x = "You win! In " + (start_chances - max_chances) + " attemps <br>";
document.getElementById("demo").innerHTML = x;
document.body.style.backgroundColor = "#009000";
endGame();
}
}
function endGame(){
document.getElementById("start").hidden = false;
document.getElementById("again").hidden = true;
document.getElementById("number").hidden = true;
}
<!DOCTYPE html>
<html>
<body>
<input type="radio" name="difficulty" onclick="ChangeDif(this.Difficulty, 'easy')">Easy
<br>
<input type="radio" name="difficulty" onclick="ChangeDif(this.Difficulty, 'medium')">Medium
<br>
<input type="radio" name="difficulty" onclick="ChangeDif(this.Difficulty, 'hard')">Hard
<br>
<h1 id="demo">You have 3 chances to guess the correct number.</h1>
<input type="number" id="number" hidden />
<button type="submit" id="start" onclick="startgame()">Let's PLAY</button>
<button type="submit" id="again" hidden onclick="lostAchance()">Try Again</button>
<p id ="cheater"></p>
</body>
</html>