First function calls on html button onclick, but not any others - javascript

I've just begun learning javascript, and I'm running into an issue where only one of my 3 currently coded buttons will either recognize a click, or run the function associated when I click it. This first example of code works wonderfully;
The HTML
<div id="commonchecks">
<h3>Common Checks:</h3>
<p>Type of Check:</p>
<select id="CheckType">
<option value="Strength">Strength</option>
<option value="Stamina">Stamina</option>
<option value="Agility">Agility</option>
<option value="Intelligence">Intelligence</option>
<option value="Charisma">Charisma</option>
<option value="Perception">Perception</option>
</select>
<p>Complexity:</p>
<select id="Complexity">
<option value="Simple">Simple</option>
<option value="Complex">Complex</option>
</select>
<p>Circumstantial Factors (+/-):</p>
<input type="number" id="bxCircumstantialFactors" value="-2">
<h3 class="details">Check Details:</h3>
<p id="success" class="details">It was a XXXXXXX!</p>
<p id="rolltotal" class="details">You rolled a(n) XX.</p>
<p id="rollstandards" class="details">You needed a(n) XX or higher.</p>
<p id="experience" class="details">Experience Payout: 00 exp!</p>
<p id="duplicate">DUPLICATE!</p>
<button onclick="CheckRoll()" class="button" id="RollCheckButton">Roll</button>
</div>
And the javascript
function CheckRoll() {
//Loading Variables Up From User Input
numStrength = Number(document.getElementById("bxStrength").value);
numStamina = Number(document.getElementById("bxStamina").value);
numAgility = Number(document.getElementById("bxAgility").value);
numIntelligence = Number(document.getElementById("bxIntelligence").value);
numCharisma = Number(document.getElementById("bxCharisma").value);
numPerception = Number(document.getElementById("bxPerception").value);
numCircumstantialFactors = Number(document.getElementById("bxCircumstantialFactors").value);
//Making the Roll
numRoll = Math.floor(Math.random() * 20 + 1);
if (document.getElementById("duplicate").style.visibility === "visible"){
document.getElementById("duplicate").style.visibility = "hidden";
}
//Checking to see if the roll was a duplicate
if (numRoll === prevRoll) {
document.getElementById("duplicate").style.visibility = "visible";
}
//Checking the complexity of the check
switch (document.getElementById("Complexity").value){
case "Simple":
numBaseAddition = 10;
numStatModifier = 2;
break;
case "Complex":
numBaseAddition = 0;
numStatModifier = 1;
break;
}
//Checking the stat associated and marking it as the calculated stat
switch (document.getElementById("CheckType").value) {
case "Strength":
numRelevantStatValue = numStrength;
break;
case "Stamina":
numRelevantStatValue = numStamina;
break;
case "Agility":
numRelevantStatValue = numAgility;
break;
case "Intelligence":
numRelevantStatValue = numIntelligence;
break;
case "Charisma":
numRelevantStatValue = numCharisma;
break;
case "Perception":
numRelevantStatValue = numPerception;
break;
}
//Determining how much value of a stat effects your chances of success
numStatAddition = numRelevantStatValue / numStatModifier;
//Determining your factor of success
numSuccessFactor = numBaseAddition + numStatAddition + numCircumstantialFactors;
//If success factor is a 20 or higher, set it to 19 since one can always roll a 1
if (numSuccessFactor >= 20){
numSuccessFactor = 19;
}
//Calculating the number you need to beat
numFailureFactor = 20 - numSuccessFactor;
//If failure factor is a 20 or higher, set it to 19 since one can always roll a 20
if (numFailureFactor >= 20) {
numFailureFactor = 19;
}
//Calculating amount of experience possible to be earned
numExperience = numFailureFactor * 5;
//Reporting on the successfulness or not
if (numRoll >= numFailureFactor + 1){
document.getElementById("success").innerHTML = "It was a SUCCESS!";
}
if (numRoll === 20){
document.getElementById("success").innerHTML = "It was a CRITICAL SUCCESS!";
}
if (numRoll < numFailureFactor + 1){
document.getElementById("success").innerHTML = "It was a FAILURE!";
numExperience = 0;
}
if (numRoll === 1){
document.getElementById("success").innerHTML = "It was a CRITICAL FAILURE!";
numExperience = 0;
}
//Reporting the dice roll
document.getElementById("rolltotal").innerHTML = "You rolled a(n) " + numRoll + ".";
//Reporting the standards
document.getElementById("rollstandards").innerHTML = "You needed a(n) " + (numFailureFactor + 1) + " or higher.";
//Reporting experience gain
document.getElementById("experience").innerHTML = "Experience Payout: " + numExperience + " exp!";
//Saving last roll
prevRoll = numRoll;
However, on a much simpler function, it won't work for whatever reason. I've tried putting the javascript into firefox's debugger, and it didn't reveal any syntax mistakes. Here's the section that won't work.
The HTML
<p class="blocksection">Block Type:</p>
<select id="blocktype">
<option value="Unarmed">Unarmed</option>
<option value="Armed">Armed</option>
</select>
<p class="blocksection" id="blockreporter">Your Block total is a(n) XX!</p>
<p class="blocksection" id="blockduplicate">DUPLICATE!</p>
<button onclick="BlockRoll()" class="button" id="blockbutton">Block!</button>
And the javascript
function BlockRoll() {
numStamina = Number(document.getElementById("bxStamina").value);
if (document.getElementById("blocktype").value === "Unarmed") {
document.getElementById("blockreporter").InnerHTML = "Your Block total is a(n) " + Math.floor(Math.random() * 6 + 1) + "!";
}
else {
document.getElementById("blockreporter").InnerHTML = "Your Block total is a(n) " + (Math.floor(Math.random() * 6 + 1) + (numStamina/2)) + "!";
}
}
I'm not used to this language, but I know c# well enough and they appear relatively similar. Is there a really simple mistake that I'm making somewhere?
Thanks

You're calling element.InnerHTML in your second example which is incorrect, as the correct value is innerHTML (note the lowercase i.)
If you hit F12 (in most browsers) the developer console will come up and show you common errors like these.

Related

I am new to javascript, and I am trying to make a html program to calculate dog age

No matter what I do, the underneath code only prints out the else and it comes out as undefined. What am I doing wrong?
function calcDogAge() {
var dogAge = document.getElementsByName("dogAge").valueOf.isNumber;
if (dogAge >= 2) {
var old = (dogAge * 4) + 13;
document.getElementsById("dogogo").innerHTML = "Your dog is " + old + "years old.";
} else if (dogAge < 2) {
var young = dogAge * 10.5;
document.getElementById("dogogo").innerHTML = "Your dog is " + young + "years old.";
} else {
document.getElementById("dogogo").innerHTML = dogAge;
}
}
<input type="number" class="dogAge" name="dogAge"/>
<button onclick = "calcDogAge()">Find dog age now</button>
<p id="dogogo"></p>
Find the fixes in comments:
const btnCalc = document.getElementById("btnCalc"), // cache your elements
dogAge = document.getElementById("dogAge"), // use the right method for DOM query
dogogo = document.getElementById("dogogo");
function calcDogAge() {
const n = parseInt(dogAge.value, 10); // input gives always a string, so use parseInt
if (n >= 2) {
var old = n * 4 + 13;
dogogo.innerHTML = "Your dog is " + old + " years old.";
} else if (n < 2) {
var young = n * 10.5;
dogogo.innerHTML = "Your dog is " + young + " years old.";
} else {
dogogo.innerHTML = n;
}
}
// Don't use inline JavaScript, instead use listeners inside your JS code
btnCalc.addEventListener('click', calcDogAge);
<input id="dogAge" type="number">
<button id="btnCalc">Find dog age now</button>
<p id="dogogo"></p>
or a slight modification:
const EL = (sel) => document.querySelector(sel),
EL_res = EL('#res'),
EL_age = EL('#age');
const calcAge = () => {
const n = parseInt(EL_age.value, 10);
let y = 0;
if (n >= 2) y = n * 4 + 13;
else if (n < 2) y = n * 10.5;
EL_res.innerHTML = `Your dog is ${y} years old.`;
};
EL("#btn").addEventListener('click', calcAge);
<input id="age" type="number">
<button id="btn">Find dog age now</button>
<p id="res"></p>
You need to replace var dogAge = document.getElementsByName("dogAge").valueOf.isNumber;
by
var dogAge = document.getElementsByName("dogAge")[0].value;
as getElementsByName returns a list of all nodes with the given name.
Also, you have a misspelled getElementByID in the first if condition

Javascript value does not change when alternative radio button is clicked

Im learning JavaScript....slowly. Im working front end for a friend and learning as I go along. I thought JavaScript would be a better starting point than Jquery so please keep that in mind when answering, unless I am wrong assuming the above.
My problem is as follows
When looking at above image you can see the estimated return has been correctly calculated for the low risk option selected.
However if user clicks High Risk radio button without moving slider and then clicks the get estimate button. the amount does not update...?
Only when user moves slider the amount will update according to radio button selected. But if radio button is changed without moving slider the amount DOES NOT UPDATE. Hope this makes sense? If not please let me know and ill be happy to clarify.
Code as follows:
Radio Buttons (shortened version)
<input type="radio" id="control_01" name="risk" value="1" checked>
<input type="radio" id="control_02" name="risk" value="2">
<input type="radio" id="control_03" name="risk" value="3">
Javascript
function getReturn() {
var risk = document.forms[0];
var slideAmount = document.getElementById("slideAmount").value;
var txt;
var returns;
var i;
for (i = 0; i < risk.length; i++) {
if (risk[i].checked) {
txt = risk[i].value;
} //for
if (txt = 1) {
returns = slideAmount * 0.06;
returns = Math.ceil(returns); // NO decimals
}
if (txt = 2) {
returns = slideAmount * 0.11;
returns = Math.ceil(returns); // NO decimals
}
if (txt = 3) {
returns = slideAmount * 0.17;
returns = Math.ceil(returns); // NO decimals
}
} //for
document.getElementById("returns").innerHTML = "ESTIMATED RETURN PA: <span style='color:red'><i class='fa fa-usd fa-lg'></i>" + returns + "</span>";
}
HTML Button on Click
<button type="button" class="btn btn-primary btn-lrg" onclick="getReturn()">GET ESTIMATE</button>
<div id="returns" style="font-weight: 800; color:black; font-size: 15px">Estimated</div>
Any advice, help and tips appreciated.
txt = 1 is not a comparison, it is an assignment. It has to be txt == 1, ... . The way you wrote it txt = 3 will always be true, because 3 is truthy.
In general you should use a linter like eslint or a code styleguide guideline tool like standardjs, those tools warn you about these common mistakes and pitfalls.
Beside that, you should write this kind of if clauses that way:
if (txt == 1) {
returns = slideAmount * 0.06;
returns = Math.ceil(returns); // NO decimals
} else if (txt == 2) {
returns = slideAmount * 0.11;
returns = Math.ceil(returns); // NO decimals
} else if (txt == 3) {
returns = slideAmount * 0.17;
returns = Math.ceil(returns); // NO decimals
}
And if possible use === instead of ==.
if (risk[i].checked) {
txt = Number(risk[i].value); // convert the value to a Number
} //for
if (txt === 1) {
returns = slideAmount * 0.06;
returns = Math.ceil(returns); // NO decimals
} else if (txt === 2) {
returns = slideAmount * 0.11;
returns = Math.ceil(returns); // NO decimals
} else if (txt === 3) {
returns = slideAmount * 0.17;
returns = Math.ceil(returns); // NO decimals
}
Solution is just not to correct your mistake, but also to reduce the number of line of code.
function getReturn() {
var risk = document.forms[0];
var slideAmount = document.getElementById("slideAmount").value;
var txt;
var returns;
for (var i = 0; i < risk.length; i++) {
if (risk[i].checked) {
txt = risk[i].value;
} //for
if (txt == 1) {
returns = slideAmount * 0.06;
} else if (txt == 2) {
returns = slideAmount * 0.11;
} else if (txt == 3) {
returns = slideAmount * 0.17;
}
} //for
document.getElementById("returns").innerHTML = "ESTIMATED RETURN PA: <span style='color:red'><i class='fa fa-usd fa-lg'></i>" + Math.ceil(returns) + "</span>";
}
= is an assignment operator, whereas == is a comparison operator.
Hope this will help you.
There are several issues with the code.
You should exit your for loop when the radio button has been found
As mentioned in several posts, = should be replaced with == in your comparators.
You have incomplete HTML leaving those offering help to make assumptions about your DOM elements. For example, <form> and <input type="range"> are missing from the example.
Below please find a sample with missing DOM elements added and simplified logic. A switch/case was used as an example because some find this easier to read. It is otherwise logically equivalent to the if/else examples.
<html>
<form>
<input type="radio" id="control_01" name="risk" value="1" checked>
<input type="radio" id="control_02" name="risk" value="2">
<input type="radio" id="control_03" name="risk" value="3">
</form>
<button type="button" class="btn btn-primary btn-lrg" onclick="getReturn()">GET ESTIMATE</button>
<div id="returns" style="font-weight: 800; color:black; font-size: 15px">Estimated</div>
<input type="range" id="slideAmount" value="1" max="100"></input>
<script>
function getReturn() {
var risk = document.forms[0];
var slideAmount = document.getElementById("slideAmount").value;
var returns;
for (var i = 0; i < risk.length; i++) {
// Skip unchecked radio buttons
if (!risk[i].checked) {
continue;
}
// Divide by one to force string to value
switch(risk[i].value/1) {
case 1:
returns = Math.ceil(slideAmount * 0.06);
break;
case 2:
returns = Math.ceil(slideAmount * 0.11);
break;
case 3:
returns = Math.ceil(slideAmount * 0.17);
break;
default:
console.error("Shouldn't have reached " + risk[i].value);
}
}
document.getElementById("returns").innerHTML = "ESTIMATED RETURN PA: <span style='color:red'><i class='fa fa-usd fa-lg'></i>" + returns + "</span>";
}
</script>
</html>
Hi please do these changes in function:
function getReturn() {
var risk = document.getElementsByName('risk'); // change
var slideAmount = document.getElementById("slideAmount").value;
var txt;
var returns;
var i;
for (i = 0; i < risk.length; i++) {
if (risk[i].checked) {
txt = risk[i].value;
} //for
if (txt === "1") { // change
returns = slideAmount * 0.06;
returns = Math.ceil(returns); // NO decimals
}
if (txt === "2") { // change
returns = slideAmount * 0.11;
returns = Math.ceil(returns); // NO decimals
}
if (txt === "3") { // change
returns = slideAmount * 0.17;
returns = Math.ceil(returns); // NO decimals
}
} //for
document.getElementById("returns").innerHTML = "ESTIMATED RETURN PA: <span style='color:red'><i class='fa fa-usd fa-lg'></i>" + returns + "</span>";
}

Inserting a loop into a Javascript number guessing game

For an assignment, I need to make a JS number guessing game. It needs to include a loop to check the user's guess and a reset game button. My problem is getting the loop to work. I want the number of turns to start at 10. Each time the user makes an incorrect guess, their number of turns decreases by 1, and if they guess correctly, their number of turns is 0. If they push the "Start New Game" button, a new number should be generated and the number of turns should be reset to 10.
The loop doesn't specifically need to be a while loop, I just need one in the code for my assignment. Can anybody help me out?
<body>
<!-- GAME INSTRUCTIONS -->
<h1>Number Guessing Game</h1>
<p>A random number between 1 and 100 has been generated. Can you guess it?</p>
<!-- FORM (Includes button to confirm guess, input box, and output box) -->
<form id="Input" name="Input">
<input name="guess" placeholder="Insert your guess" type="number">
<input name="requestInfo" onclick="getResults()" type="button" value="Confirm">
<p></p>
<textarea cols="50" name="results" readonly="true" rows="8"></textarea>
<p></p><input name="newGame" onclick="resetGame()" type="button" value="Start New Game">
</form><!-- JAVASCRIPT START -->
<script type="text/javascript">
// Define variables
var num = Math.floor(Math.random() * 100) + 1;
var turns = 10;
function checkNumber() {
var guess = parseFloat(document.Input.guess.value);
while (turns > 0) {
if (guess == num) {
turns = 0;
document.Input.results.value = "Congratulations, you won! The mystery number was " + num + ".";
} else if (guess < num) {
turns--;
document.Input.results.value = "Your guess was too low. Turns remaining: " + turns;
} else if (guess > num) {
turns--;
document.Input.results.value = "Your guess was too high. Turns remaining: " + turns;
}
}
}
function resetGame() {
turns = 10;
num = Math.floor(Math.random() * 100) + 1;
document.Input.guess.value = "";
document.Input.results.value = "";
}
function getResults() {
checkNumber();
}
</script>
</body>
Alright, I guess since it is a college/HS assignment your professor is trying to teach you using prompt under a loop.
<body>
<!-- GAME INSTRUCTIONS -->
<h1>Number Guessing Game</h1>
<p>A random number between 1 and 100 has been generated. Can you guess it?</p>
<!-- FORM (Includes button to confirm guess, input box, and output box) -->
<form id="Input" name="Input">
<input name="requestInfo" onclick="getResults()" type="button" value="Start Guessing!">
<input name="newGame" onclick="resetGame()" type="button" value="Start New Game">
</form><!-- JAVASCRIPT START -->
<script type="text/javascript">
// Define variables
var num = Math.floor(Math.random() * 100) + 1;
var turns = 10;
function checkNumber() {
while (turns > 0) {
guess=prompt("Tell me your guess.", "Your guess: ");
if (guess == num) {
turns = 0;
alert("Congratulations, you won! The mystery number was " + num + ".");
} else if (guess < num) {
turns--;
alert("Your guess was too low. Turns remaining: " + turns);
} else if (guess > num) {
turns--;
alert("Your guess was too high. Turns remaining: " + turns);
}
}
if (turns==0)
alert ("You failed to guess sadly.");
}
function resetGame() {
turns = 10;
num = Math.floor(Math.random() * 100) + 1;
}
function getResults() {
checkNumber();
}
</script>
I agree that the taks seems a bit weird - obviously, with a non-modal dialog, you will not need a loop.
One thing you could do is use the prompt method (example: window.prompt("sometext","defaultText");), which would then open a modal dialog to ask the user until the number of remaining guesses is zero, or until the guess was correct. That would work within the loop.
Here have a go with this one. Makes sure that the user enters a number.
<body>
<!-- GAME INSTRUCTIONS -->
<h1>Number Guessing Game</h1>
<p>A random number between 1 and 100 has been generated. Can you guess it? Click button to start game.</p>
<button type="button" onclick="startNewGame()">Start New Game</button>
<script type="text/javascript">
// Define variables
var num = Math.floor(Math.random() * 100) + 1;
var turns;
function checkNumber() {
while (turns > 0) {
var guess = prompt("Insert your guess");
if (!guess || isNaN(guess)) {
alert("Please enter a valid number");
continue;
}
if (guess == num) {
alert("Congratulations, you won! The mystery number was " + num + ".");
return;
} else {
turns--;
if (guess < num) {
alert("Your guess was too low. Turns remaining: " + turns);
} else if (guess > num) {
alert("Your guess was too high. Turns remaining: " + turns);
}
}
}
if (turns == 0) {
alert("You have lost");
}
}
function startNewGame() {
turns = 10;
num = Math.floor(Math.random() * 100) + 1;
checkNumber();
}
</script>
</body>

Trouble with html input box

I'm making a basic usd converter for practice in html/javascript.
However when I select the euro option it does the same as for the peso option.
<html>
<head>
<title>Currency Converter</title>
<style>
</style>
</head>
<body>
<input id="amount"> </input>
<p>usd Contverted to</p>
<p class="output"> </p>
<select id="select"> <option value="1">Peso's</option> <option value="2">Euro's</option> </select>
<p id="answer"> is </p>
<input type="submit" value="Submit" onclick="run()">
<script>
function run() {
var Amount = document.getElementById("amount").value;
if (select = 1) {
document.getElementById("answer").innerHTML = "=-=-= " + Amount * 16.39 + " =-=-=";
} else if (select = 2) {
document.getElementById("answer").innerHTML = "=-=-= " + Amount * 0.9 + " =-=-=";
} else {
}
</script>
</body>
</html>
You are not comparing select,you are setting it.
if (select == 1) {
document.getElementById("answer").innerHTML = ...
} else if (select == 2) {
= -> setting a value
== -> comparing
it should be select == 1
select=1 will always return true, because this way you are simply assigning a value, not checking for equality
You are not getting value of select
You are not comparing select value in if condition, make it as select == 1 and select == 2
Complete solution here
Change your javaScript function as below
function run() {
var Amount=document.getElementById("amount").value;
var select=document.getElementById("select").value;
if (select == 1) {
document.getElementById("answer").innerHTML = "=-=-= " + Amount * 16.39 + " =-=-=";
} else if (select == 2) {
document.getElementById("answer").innerHTML = "=-=-= " + Amount * 0.9 + " =-=-=";
} else {
}
}

JavaScript Doesn't Output Any Value

Recently I've started learning JavaScript in use with HTML. I wanted to create a simple calculator for a game I am using. You select a type of ore, the amount of the ore left in the asteroid, the value mined each cycle, and the duration of one cycle, and the script is supposed to return the volume of ore to be mined and number of cycles required as well as their total duration.
I've tried several things, like enclosing the function in try statement, but that didn't work either. I am asking for your help trying to figure out what I did wrong and point me in the right way. Thanks in advance.
<html>
<head>
<title>Mining Calculator - IndX: Industry Extension</title>
<script type="text/javascript">
function oreCalc() {
var ore = document.getElementById("ores").value;
var volume;
var amount = document.getElementById("amnt").value;
var yield = document.getElementById("yield").value;
var cycle = document.getElementById("cycle").value;
try{
switch(ore){
case "veldspar":
volume = 0.1;
break;
case "scordite":
volume = 0.15;
break;
case "pyroxeres":
volume = 0.3;
break;
case "plagioclase":
volume = 0.35;
break;
case "omber":
volume = 0.6;
break;
case "kernite":
volume = 1.2;
break;
case "jaspet":
volume = 2;
break;
case "hemorphite":
volume = 3;
break;
case "gneiss":
volume = 5;
break;
case "dark_ochre":
volume = 8;
break;
case "spodumain":
volume = 16;
break;
case "crokite":
volume = 16;
break;
case "arkonor":
volume = 16;
break;
case "mercoxit":
volume = 40;
break;
}
var rockvolume = amount * volume;
var cycles = rockvolume / yield;
var seconds = cycles * cycle;
var minutes;
while(seconds > 60)
{
seconds -= 60;
minutes++;
}
var text = "The asteroid has " + rockvolume + " m3 of ore. \n You'll mine it in " + Math.ceil(cycles) +
" cycles. \n It will take you " + minutes + "min " + Math.ceil(seconds) "s to mine.";
document.getElementById("output").innerHTML = text;
}
catch(err){
var text = "Input all required fields";
document.getElementById("output").innerHTML = text;
}
}
</script>
</head>
<body>
<table><tr><td>Ore:</td><td>
<select name="ores" id="ores" onchange="oreCalc()">
<option value="veldspar">Veldspar</option>
<option value="scordite">Scordite</option>
<option value="pyroxeres">Pyroxeres</option>
<option value="plagioclase">Plagioclase</option>
<option value="omber">Omber</option>
<option value="kernite">Kernite</option>
<option value="jaspet">Jaspet</option>
<option value="hemorphite">Hemorphite</option>
<option value="gneiss">Gneiss</option>
<option value="dark_ochre">Dark Ochre</option>
<option value="spodumain">Spodumain</option>
<option value="crokite">Crokite</option>
<option value="arkonor">Arkonor</option>
<option value="mercoxit">Mercoxit</option>
</select></td><td rowspan="4"><p id="output"></p></td></tr>
<tr><td>Amount:</td><td>
<input type="number" name="amount" id="amnt" oninput="oreCalc()">
</td></tr>
<tr><td>Yield:</td><td>
<input type="number" name="yield" id="yield" oninput="oreCalc()">
</td></tr>
<tr><td>Cycle duration:</td><td><input type="number" name="cycle" id="cycle" oninput="oreCalc()"></td></tr>
</table>
</body>
</html>
To track down these sorts of problems you need to use your browser's error console.
In Firefox it's Menu -> Developer -> Web Console
In Chrome it's Menu -> More Tools -> Javascript Console
In IE I think you hit F12 a click console.
I'm using Firefox and I see the following error on your page:
SyntaxError: missing ; before statement ore.html:66
And if you go to around line 66 you'll see:
var text = "The asteroid has " + rockvolume + " m3 of ore. \n You'll mine it in " + Math.ceil(cycles) +
" cycles. \n It will take you " + minutes + "min " + Math.ceil(seconds) "s to mine.";
Note the missing "+" after Math.ceil(seconds) but before "s to mine."? Add the plus sign and it should now work.
Btw, it's often better to use an external file for Javascript. I find it makes it much easier to manage and track down issues.

Categories