Javascript Exponents in HTML - javascript

I need to create a JavaScript function that uses input=number to pass it to a JavaScript function to raise it to 2nd, 3rd, 4th, and 5th powers. So far I can pass a number to it and out put that number, but can not seem to grasp the math.pow and also how to get all the other powers. Here is what I have so far.
<!DOCTYPE html>
<html>
<body>
<h1>Opponents!? More Like Ex-Ponents</h1>
<input type="number" id="myNumber" value="0">
<p>Click the button to get the exponents of the number field.</p>
<button onclick="myFunction()">Calculate</button>
<p id="demo"></p>
<script>
function myFunction() {
var x = document.getElementById("myNumber").value;
document.getElementById("demo").innerHTML = x;
}
</script>
</body>
</html>
I'm not able to just input values. I need to be able to take a value that was input by the user and do the calculations on it. I've tried this with little results.
<script>
function myFunction() {
var x = document.getElementById("myNumber").value;
var y = math.pow(x,2);
document.getElementById("demo").innerHTML = y;
}
</script>

Math.pow works like so:
Math.pow(value, exponent)
so if I wanted to raise 5 by 11 I would do:
Math.pow(5,11)
Just replace the numbers with the variables you're using for value and exponent

Related

Javascript - Calculate average of numbers

pretty new here and in programming overall so I would really appreciate some help.
Now, I want to create a site that has a button which calls a function when clicked. This function brings up a prompt box that allows the user to insert numbers only, infinitely or until he clicks cancel on the prompt box or presses space.
When the insertion of the numbers has stopped, the function calculates the average of all the numbers inserted and displays the result on an alert box. I have tried it and here's my code so far.
<html>
<head>
<script type="text/javascript">
function calc_avg() {
var avg; var sum;var total;var num=1;
while (num>0) {
var x = parseInt(prompt("Please enter a number","0"))
if (x=="") {
break;
} else {
sum += x;
total++;
avg=sum/total;
window.alert(avg);
}
}
}
</script>
</head>
<body>
<form>
<input type="button" onclick="calc_avg()" value="Calculate Average">
</form>
</body>
</html>
Thanks in advance!

Imroving the javascript code

I have a piece of code to calculate power of a number, The code is working fine for me but i am not sure if it is good performance wise.
<html>
<head>
<SCRIPT>
function power(){
var number = document.getElementById("number").value;
var power = document.getElementById("power").value;
var newNumber = number;
for(var i=0; i<(power-1);i++){
newNumber *= number;
}
document.getElementById("output").innerHTML= newNumber;
}
</SCRIPT>
</head>
<body>
<input type="text" id ="number" placeholder="Enter number">
<input type="text" id ="power" placeholder="Enter power">
<input type="submit" onclick = "power()">
<p id ="output"></p>
</body>
</html>
I have changed my code to this -
function power(){
var number = document.getElementById("number").value;
var power = document.getElementById("power").value;
number = Math.pow(number,power)
document.getElementById("output").innerHTML= number;
}
You can use Math.pow(base, exponent):
The Math.pow() function returns the base to the exponent Power, that
is, baseexponent.
I have to point out, that your solution using the for-loop only works when power is a positive integer. It returns a wrong value for all non-integer powers and when power < 1. That is why using Math.pow() is a wise choice.
Your code, if you dont want to use Math.pow is "optimized" you can't get better performance without using Math.pow.

Why this javascript and html code is not calculating the result?

This is the code:
<html>
<body>
<script>
function myFunction(var1,var2){
number=var1+var2
document.write(number)
}
</script>
<form>
Number 1 : <input type="text" name="no1"><br>
Number 2 : <input type="text" name="no2"><br>
<input type="button" onclick="myFunction(this.form.no1.value,this.form.no2.value)" value="submit">
</form>
<p id="demo></p
</body>
</html>
When I insert 10 for number 1 and 20 for number 2, the output is:
1020
But i want it to display 30.
What can i do?
**I have tried myFunction(10,20), the result is 30.
simply use parse the variable value to integer using parseInt() method or add "+"before to your variable name. Because variables var1 and var2 returning string. To calculate those variable values, you need to convert it as a integer.
using parseInt() method
number=parseInt(var1)+parseInt(var2)
use + before variable name to convert into integer,
number= +var1 + +var2
try this code,
<html>
<body>
<script>
function myFunction(var1,var2){
number = parseInt(var1) + parseInt(var2)
//another way number= +var1+ +var2
document.write(number)
}
</script>
<form>
Number 1 : <input type="text" name="no1"><br>
Number 2 : <input type="text" name="no2"><br>
<input type="button" onclick="myFunction(this.form.no1.value,this.form.no2.value)" value="submit">
</form>
<p id="demo"></p>
</body>
</html>
using parseInt() DEMO
using + before variable name DEMO
modify your function with parseInt like:
<script>
function myFunction(var1,var2){
number=parseInt(var1)+parseInt(var2);
document.write(number);
}
</script>
You were getting output like 1020 because by default data from the textbox is taken as text type, so we need to convert it to Number Type first, for that we are using parseInt(for explicit conversion)
Your javascript thinks you are appending strings... To make sure your javascript knows it's numbers your working with you need to convert it to that type.
<html>
<body>
<script>
function myFunction(var1, var2){
number = parseInt(var1, 10) + parseInt(var2, 10)
document.write(number)
}
</script>
<form>
Number 1 : <input type="text" name="no1"><br>
Number 2 : <input type="text" name="no2"><br>
<input type="button" onclick="myFunction(this.form.no1.value,this.form.no2.value)" value="submit">
</form>
<p id="demo"></p>
</body>
</html>
For more info about parseInt check this documentation.
Update your method to
function myFunction(var1,var2){
number=parseInt(var1) + parseInt(var2)
document.write(number)
}
As this.form.no1.value is returning a string, so both the numbers are concatenated as strings instead of summing up as numbers.
Two options:
Change your input tag to
<input type="button" onclick="myFunction(parseInt(this.form.no1.value, 10),parseInt(this.form.no2.value, 10))" value="submit">
OR
Change your JavaScript function to
function myFunction(var1,var2){
var number=parseInt(var1, 10)+parseInt(var2, 10);
document.write(number);
}
It is because the values you extract from your input fields are strings. When you add two strings, they are usually concatenated. Try looking at the javascript method parseIntas Evan suggests in the comments or look at parseFloatif you want to allow floats.
parseFloat docs
Your method would then look like this:
function myFunction(var1,var2){
number = parseFloat(var1) + parseFloat(var2)
document.write(number)
}
It's now just string concatenation. Please use "parseInt()" to get the result.
thanks.
Your not doing a calculation, you are appending two Strings. In order to calculate the mathematical answer for var1 + var2 you should parse them to Integers.
result = parseInt(var1) + parseInt(var2);

Javascript Random Number Generator comes up with NaN

I am trying to make a random number generator using a form. When you press the button, and enter in the maximum number, it comes up with a dialog box reading NaN, when it is meant to come up with the random number.
I have some code that looks like this:
<html>
<head>
</head>
<body>
<form name="gen">
<h1>Random Number Generator</h1>
<b>Number:</b> 1 to
<input id="numgen" type="text"/>
<button name="generate" type="submit" onclick="gennum()">Generate!</button>
<script>
function gennum()
{
alert(Math.floor(Math.random() * num.value + 1));
}
var num = document.getElementById('numgen').value;
</script>
</form>
</body>
</html>
I am not very good with Javascript, but I know a bit. If anyone knows how to fix this, I would be happy.
num.value is a string. Use parseInt(num.value, 10) to turn it into a number, that way it can be added to a number appropriately.
Also, it looks like you're getting the value twice, and the first time is when the page loads (so it doesn't have a value yet:
var numElem = document.getElementById('numgen'); //remove value here
then in your function:
alert(Math.floor(Math.random() * parseInt(num.value + 1)));
and, you need to use type="button" on your button, or the page will reload.
Here's your code refactored with better practices.
Live demo here (click).
Markup:
<form name="gen">
<h1>Random Number Generator</h1>
<b>Number:</b> 1 to
<input id="numgen" type="text"/>
<button id="generate" type="button">Generate</button>
</form>
JavaScript:
/* get element references */
var genButton = document.getElementById('generate');
var numInput = document.getElementById('numgen');
//use javascript to add the click function
genButton.addEventListener('click', function() {
/* it's easier to read and debug if you break things up
* instead of putting it all on one line with tons of ((()))
*/
var rand = genRandom(1, parseInt(numInput.value, 10));
alert(rand);
});
function genRandom(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}

result of input box times 2 appears in window not div

I'm trying to get a text box where you can enter a number and then you click the button and it will multiply it by two and display that result in theDiv. Right now, it opens a new page for the result, and displays the entered number, not the number times two. What am I doing wrong? Beginner here, please be gentle! Thank you!!
<html>
<script>
function doubleit()
{
var theNumber=document.write(parseFloat(document.getElementById('theInput').value));
var doubleNumber =document.getElementById('theNumber')*2;
document.getElementById('theDiv').innerHTML(document.getElementById('doubleNumber'))
}
</script>
<body>
<p>Value: <input type="text" id="theInput" value="" size=10>
<input type="button" id="theButton" value="click me!" onclick="doubleit()"></p>
<div id="theDiv"></div>
</body>
</html>
It's the call to document.write that is replacing the page. Remove it:
var theNumber=parseFloat(document.getElementById('theInput').value);
When you want the value of a variable, you shouldn't use document.getElementById:
var doubleNumber = theNumber * 2;
innerHTML is a property, not a method:
document.getElementById('theDiv').innerHTML = doubleNumber;
var doubleNumber = Number(theNumber, 10)*2;
document.getElementById('theDiv').innerHTML(doubleNumber);
Something like this
function doubleit()
{
var theNumber=parseFloat(document.getElementById('theInput').value) * 2;
document.getElementById('theDiv').innerHTML = theNumber;
}
Try This Solution :
Use the id of your button to call the function to calculate result.
theButton.onclick = function doubleit()
{
//Simply get the number from user and parse it as float.
var theNumber=parseFloat(document.getElementById('theInput').value);
//Multiply it with 2
var doubleNumber =theNumber*2;
//Display the result in another div
document.getElementById('theDiv').innerHTML = doubleNumber;
}
Demo

Categories