Trying to display numbers on a calc but it says it isnt a function. I've used Number(variable.toFixed(x)) before but this time it doesnt seem to work inside of a document.getlementbyid. Any help?
if (vi === 0){
document.getElementById('result').innerHTML =
Number(reactant.toFixed(13));
} else if (vi >= 1 && tx === 0) {
document.getElementById('result').innerHTML =
Number(reactant2.toFixed(13));
} else if (vi >= 1 && tx > 0) {
document.getElementById('result').innerHTML =
Number(reactantspec.toFixed(13));
}
I am unsure of where reactant is coming from, but more than likely, it's a string value instead of a number.
"11.12123".toFixed(2); <-- toFixed is not a function error (becuase "11.12" is a string)
11.12123.toFixed(2); <-- Success!
You may need to convert your string to a number before running your toFixed logic:
Number("11.123").toFixed(2)
Have a look at the example below.
Hope it helps.
<!DOCTYPE html>
<html>
<body>
<p>Click the button to display the fixed number.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var reactant = '5.5678935436453256434';
var n = Number(reactant).toFixed(13);
document.getElementById("demo").innerHTML = n;
}
</script>
</body>
</html>
The return value from the element id i.e document.getElementById('result').innerHTML is a String, you should convert it to an integer using parseInt()
Related
I am new to JS and was trying to practice conditionals when I ran into this really weird problem.
Each conditional is working as intended in the sense that when the desired condition is met, the code is executed, for example, console.log() is outputting exactly what I want it to but trying to output the same to HTML is not working for some reason.
My code:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.3.min.js"></script>
<title>Tester</title>
</head>
<body>
<p id="test"></p>
<script>
const max = 5;
const ranNumber = Math.floor(Math.random() * max) + 1;
console.log(ranNumber);
let correct = false;
while (!correct) {
let guess = prompt("Guess a Number 1 - " + max);
guess = Number(guess);
if (guess === ranNumber) {
correct = true;
$("#test").html("Your guess was correct!");
} else if (guess > ranNumber) {
$("#test").html("Your guess was too high!");
} else {
document.getElementById("test").innerHTML = "Your guess too low!";
}
}
</script>
</body>
</html>
Now, I am using Jquery to write the HTML to the p tag but I also tried it like this:
<!DOCTYPE html>
<html>
<head>
<title>Tester</title>
</head>
<body>
<p id="test"></p>
<script>
const max = 5;
const ranNumber = Math.floor(Math.random() * max) + 1;
console.log(ranNumber);
let correct = false;
while (!correct) {
let guess = prompt("Guess a Number 1 - " + max);
guess = Number(guess);
if (guess === ranNumber) {
correct = true;
document.getElementById("test").innerHTML = "Your guess was correct!";
} else if (guess > ranNumber) {
document.getElementById("test").innerHTML =
"Your guess was too high!";
} else {
document.getElementById("test").innerHTML = "Your guess too low!";
}
}
</script>
</body>
</html>
Your page can't load while you're in the while loop and using prompt halts your javascript until it gets an input. Here's a link to a similar question that was asked:
https://www.reddit.com/r/webdev/comments/p8vod8/very_new_to_js_why_does_the_html_text_not_load/
A much better way which is also pretty easy is using an input field and a button. the onclick option runs your function
<input type="number" id="input">
<button onclick="guess()">Guess</button>
And your javascript can look like this
const max = 5
const ranNumber = Math.floor(Math.random() * max) + 1
console.log(ranNumber)
function guess(){
let input = document.getElementById('input').value
let text = document.getElementById('test')
if(input == ranNumber){
text.innerHTML = "You guessed it!"
}
else{
text.innerHTML = "Wrong!"
}
}
The fact that yr code does work! can be seen in the debugger,
but only that the loop runs to fast that you can't see it,
Congrats, for your use of 'const, Number(),' guess === ranNumber assignment operator given that, you say U are new to JS
So to output it to Html, you would need a little bit of adjustment!
I'm doing one of those codding maze challenges and I got stuck as I decoded a base64 image which contained a code block that i need to use to progress though, I'm not sure how to use it.(I know nothing about frontend languages so I assume its some form of js or api call)
function solutionChecker(url, queryParams, method, headers){
var a = headers[queryParams.b];
var altwo = a < 2;
if(!alttwo){
headers.clue="output";
}
return a == c && method === "PATCH";
}
Seems like javascript.
You can embed in a simple html and try it.
NOTE: Supply valid parameters to run the function properly...
<!DOCTYPE html>
<html>
<head>
<script>
function otherFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
function solutionChecker(url, queryParams, method, headers){
var a = headers[queryParams.b];
var altwo = a < 2;
if(!alttwo){
headers.clue="output";
}
return a == c && method === "PATCH";
}
</script>
</head>
<body>
<h2>JavaScript in Head</h2>
<p id="demo">A Paragraph.</p>
<button type="button" onclick="solutionChecker('someUrl',params,'METOD',headers)">Try it</button>
</body>
</html>
My aim is to use a single input to collect numbers and strings then use it to determine a math operation.
For example, I parse in values such as √64 intending to find the square root of 64. Knowing that this is no valid javascript, so I decided to get the first character with result[0]; which is "√" and then slice out the remaining values with result.slice(1); which is "64", then when the condition that result[0] == "√" is true then Math.sqrt(sliceVal) . This seems perfect and runs well in a mobile editor, but doesn't run in any web browser.
function actn() {
var input = document.getElementById("input").value;
var display = document.getElementById("display");
var result = input.toString();
var firstVal = result[0];
if (firstVal == "√") {
var sliceVal = result.slice(1);
display.innerHTML = Math.sqrt(sliceVal);
}
}
I do not know why It is not running at your end but It is working perfectly according to your requirement I tested above code :)
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function actn() {
var input = document.getElementById("test").value;
var result = input.toString();
var firstVal = result[0];
if (firstVal == "√") {
var sliceVal = result.slice(1);
alert(Math.sqrt(sliceVal));
}
alert("No match found");
}
</script>
</head>
<body>
<input type="text" id="test" />
<button type="button" onclick="actn()">Test</button>
</body>
</html>
Checking ASCII value instead of character comparison should work.
<html>
<body>
<input type="text" id="input" />
<button type="button" id="sqrRoot">Square Root</button>
<h1 id="display"></h1>
<script>
function actn() {
var input = document.getElementById("input").value;
var display = document.getElementById("display");
var result = input.toString();
var firstVal = result[0];
/* Ascii value for √ is 8730 */
if (firstVal.charCodeAt(0) === 8730) {
var sliceVal = result.slice(1);
display.innerHTML = Math.sqrt(sliceVal);
}
}
document.getElementById("sqrRoot").addEventListener("click", function () {
actn();
});
</script>
</body>
</html>
This is the full code:
<html>
<head>
<script type='text/javascript'>
var banners = ["Red.jpg","Amber.jpg","Green.jpg"];
var bnrCntr = 0;
var timer;
function banCycle()
{
if(++bnrCntr == 3)
bnrCntr = 0;
document.images.banner.src = banners[bnrCntr];
timer = setTimeout("banCycle()",1000);
}
function stopCycle()
{
clearTimeout(timer);
}
</script>
</head>
<body>
<img src="Red.jpg" name="banner" width=110 height=200>
<form>
<input type="button" value="Cycle" name="Cycle" onclick="banCycle()">
<input type="button" value="Stop" name="Stop" onclick="stopCycle()">
</form>
</body>
</html>
It is the line that I don't understand:
if(++bnrCntr == 3)
Can anyone tell me what this line does?
The line
if (++bnrCntr == 3)
does the same thing as
if ((bnrCntr += 1) == 3)
or
bnrCntr = bnrCntr + 1;
if (bnrCntr == 3)
The value of bnrCntr is incremented, and the result is then assigned back to the variable. Then the value is compared to 3. The ++ operator is called the prefix increment operator.
It first increases the bnrCntr value by 1 and if that value equals to 3 it's set back to 0. You get circular banner changing this way. You could also write it this way, so it's more understandable:
if (++bnrCntr == banners.length)
bnrCntr = 0;
So, when the index goes out of the bounds of the array, start from the beginning.
I need to fix this segment of code for a class and I have fixed a number of things but I'm not sure why it doesn't work. It is supposed to count the number of vowels in the phrase and return them as an alert. When I click on the button nothing appears.
Here's the html. It works fine but added in case I am missing something
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Vowels</title>
<link rel="stylesheet" href="../css/easy.css">
<script src="p3-vowels.js"></script>
</head>
<body>
<header>
<h1>Count Vowels</h1>
</header>
<main>
<label>Type a phrase here:
<input type='text' id='textBox'></input>
</label>
<button id='countBtn' type='button'>
Count Vowels (a,e,i,o,u)</button>
<div id='outputDiv'></div>
</main>
</body>
</html>
here is the JS. It doesn't seem to register the "on.click" at the end of the code
function countVowels() {
var textBox, phrase, i, pLength, letter, vowelCount;
textBox = document.getElementById('textBox');
phrase = textBox.value;
phrase = phrase.toLowerCase();
vowelCount = 0;
for (i = 0; i < phrase.length; i += 1) {
letter = phrase[i];
if (letter === 'a' || letter === 'e' || letter === 'i' || letter === 'o' || letter === 'u') {
vowelCount++;
}
}
alert(vowelCount + ' vowels');
var outArea = document.getElementById('outputDiv');
outArea.innerHTML = vowelCount + ' vowels in ' + phrase;
}
function init() {
alert('init vowels');
var countTag = document.getElementById('countBtn');
countTag.onclick = countVowels;
}
window.onload = init();
The problem is window.onload = init();, here you are calling init method and is assigning the value returned by init as the onload callback. So when the init method is called the countBtn is not yet added to the dom resulting in an error like Uncaught TypeError: Cannot set property 'onclick' of null.
What you really want is to call init on the load event, so you need to pass the reference to init function to onload
It should be
window.onload = init;
Demo: Fiddle