I have been trying to get a random number generator for the numbers to be between the two inputs. I have a code
<form action="/action_page.php">
<input type="number" name="low" id="low" placeholder="lowest number" value="1"><br>
<input type="number" name="high" id="high" placeholder="highest number" value="10"><br>
<input type="button" value="Submit" onclick="myFunction()">
</form>
<p id="randnum"></p>
<script>
function myFunction() {
var x = document.getElementById("randnum")
x.innerHTML = Math.floor((Math.random() * 'low') + 'high');
}
</script>
As you would have noticed, I have the javascript in the one code.
where I put in 'low' and 'high' works with a fixed number
You need to get the value of the inputs and apply them to the calculations. - note that i am using parseInt() to convert the input values to numbers. Also - using 1 will as the low value will always yield are result of 10 since your getting the math.floor - which will equate to 0 - so 0 + 10 = 10.
Based on #Quentins comment - i alered the caluclation to suit your numbers.
function myFunction() {
var x = document.getElementById("randnum");
var high = parseInt(document.getElementById("high").value);
var low = parseInt(document.getElementById("low").value);
x.innerHTML = Math.floor(Math.random()*(high-low+1)+low)
}
<form action="/action_page.php">
<input type="number" name="low" id="low" placeholder="lowest number" value="1"><br>
<input type="number" name="high" id="high" placeholder="highest number" value="10"><br>
<input type="button" value="Submit" onclick="myFunction()">
</form>
<p id="randnum"></p>
<form action="/action_page.php">
<input type="number" name="low" id="low" placeholder="lowest number" value="1"><br>
<input type="number" name="high" id="high" placeholder="highest number" value="10"><br>
<input type="button" value="Submit" onclick="myFunction()">
</form>
<p id="randnum"></p>
<script>
myFunction = () => {
let min = parseInt(low.value, 0);
let max = parseInt(high.value, 0);
let x = document.getElementById("randnum")
x.innerHTML = Math.floor(Math.random() * (max - min)) + min;
}
</script>
I think this will help.
<form action="/action_page.php">
<input type="number" name="low" id="low" placeholder="lowest number" value="1"><br>
<input type="number" name="high" id="high" placeholder="highest number" value="10"><br>
<input type="button" value="Submit" onclick="myFunction()">
</form>
<p id="randnum"></p>
<script>
function myFunction() {
var x = document.getElementById("randnum")
var low = document.getElementById("low").value;
var high = document.getElementById("high").value;
x.innerHTML = Math.floor((Math.random() * low) + high);
}
</script>
var max = parseInt($("#high")[0].value);
var min = parseInt($("#low")[0].value);
x.innerHTML = Math.floor(Math.random() * max) + min;
First, in (Math.random() * 'low') + 'high', low and high are not really the integer values.
Second, a very IMPORTANT issue others did not mention is that Math.random() returns a double value between 0 and 1. If you follow some of the other answers, the random number will always be 0.
use this:
<form action="/action_page.php">
<input type="number" name="low" id="low" placeholder="lowest number"
value="1"><br>
<input type="number" name="high" id="high" placeholder="highest number"
value="10"><br>
<input type="button" value="Submit" onclick="myFunction()">
</form>
<p id="randnum"></p>
<script>
function myFunction() {
var x = document.getElementById("randnum")
var low = document.getElementById("low").value;
var high = document.getElementById("high").value;
var random = Math.random();
x.innerHTML = Math.floor(random * (high-low) + high);
}
</script>
Related
I want display div id="showResult" after click calculate button and clear all input and div id="showResult" after click clear button in a form. But clear button doesn't work after I click the button.
What's the problem? How can I solve this problem?
window.onload = function BMR() {
var gender = document.getElementById('gender');
var weight = document.getElementById('weight');
var height = document.getElementById('height');
var age = document.getElementById('age');
var calculate = document.getElementById('calculate');
calculate.addEventListener('click', toBmr);
function toBmr() {
var select = null;
if (gender.value && weight.value && height.value && age.value) {
if (document.getElementById('gender').checked) {
select = document.getElementById('gender').value;
}
if (select == 'male') {
var result = (10 * weight.value) + (6.25 * height.value) - (5 * age.value) + 5;
document.getElementById('result').innerHTML = Number(result).toFixed(2);
} else {
var result = (10 * weight.value) + (6.25 * height.value) - (5 * age.value) - 161;
document.getElementById('result').innerHTML = Number(result).toFixed(2);
}
document.getElementById('showResult').style.display = "block";
} else {
result = " ";
}
};
};
function clearForm() {
document.getElementById("do-form").reset();
}
<form name="do-form" id="do-form">
<p>BMR Calculator</p>
<p>Gender:
<input type="radio" id="gender" name="gender" value="male" checked="checked">Male
<input type="radio" id="gender" name="gender" value="female">Female
</p>
<p>Weight: <input type="number" name="weight" id="weight" size="10" maxlength="6" onkeypress="if(this.value.length > 5) return false;"> kg</p>
<p>Height: <input type="number" name="height" id="height" size="10" maxlength="6" onkeypress="if(this.value.length > 5) return false;"> cm</p>
<p>Age: <input type="number" name="age" id="age" size="10" maxlength="3" onkeypress="if(this.value.length > 2) return false;"></p>
<button type="button" id="calculate">Calculate</button>
<button type="button" id="clear" onclick="clearForm()">Clear</button><br><br>
<div class="row-result-tab" id="showResult" style="display:none;">
<label>BMR = <span id="result"></span> calories/day</label>
</div>
</form>
You needed to hide the div in the clearForm
Here is your code cleaned up based on the DRY principle (don't repeat yourself)
We could get rid of some testing if we could trust the browser to respect the type="number" which is fairly well supported
window.addEventListener("load", () => {
document.getElementById('calculate').addEventListener('click', toBmr);
});
const toBmr = () => {
const gender = document.querySelector('[name=gender]:checked').value;
// the "number" fields will not allow other data than numbers
let weight = +document.getElementById('weight').value;
let height = +document.getElementById('height').value;
let age = +document.getElementById('age').value;
if (weight && age && height) {
let result = (10 * weight) + (6.25 * height) - (5 * age)
result += gender === 'male' ? 5 : -161; // add 5 for male, subtract 161 if female
document.getElementById('result').innerHTML = result.toFixed(2);
document.getElementById('showResult').style.display = "block";
}
};
const clearForm = () => {
document.getElementById("do-form").reset();
document.getElementById('showResult').style.display = "none";
}
<form name="do-form" id="do-form">
<p>BMR Calculator</p>
<p>Gender:
<input type="radio" name="gender" value="male" checked="checked">Male
<input type="radio" name="gender" value="female">Female
</p>
<p>Weight: <input type="number" name="weight" id="weight" size="10" maxlength="6" onkeypress="if(this.value.length > 5) return false;"> kg</p>
<p>Height: <input type="number" name="height" id="height" size="10" maxlength="6" onkeypress="if(this.value.length > 5) return false;"> cm</p>
<p>Age: <input type="number" name="age" id="age" size="10" maxlength="3" onkeypress="if(this.value.length > 2) return false;"></p>
<button type="button" id="calculate">Calculate</button>
<button type="button" id="clear" onclick="clearForm()">Clear</button><br><br>
<div class="row-result-tab" id="showResult" style="display:none;">
<label>BMR = <span id="result"></span> calories/day</label>
</div>
</form>
The result div can not auto hide, you need add code to hide it
document.getElementById('showResult').style.visibility = "hidden";
or
document.getElementById('showResult').style.display= "none";
window.onload = function BMR() {
var gender = document.getElementById('gender');
var weight = document.getElementById('weight');
var height = document.getElementById('height');
var age = document.getElementById('age');
var calculate = document.getElementById('calculate');
calculate.addEventListener('click', toBmr);
function toBmr() {
var select = null;
if (gender.value && weight.value && height.value && age.value) {
if (document.getElementById('gender').checked) {
select = document.getElementById('gender').value;
}
if (select == 'male') {
var result = (10 * weight.value) + (6.25 * height.value) - (5 * age.value) + 5;
document.getElementById('result').innerHTML = Number(result).toFixed(2);
} else {
var result = (10 * weight.value) + (6.25 * height.value) - (5 * age.value) - 161;
document.getElementById('result').innerHTML = Number(result).toFixed(2);
}
document.getElementById('showResult').style.display = "block";
} else {
result = " ";
}
};
};
function clearForm() {
document.getElementById("do-form").reset();
//document.getElementById('showResult').style.visibility = "hidden";
document.getElementById('showResult').style.display = "none";
}
<form name="do-form" id="do-form">
<p>BMR Calculator</p>
<p>Gender:
<input type="radio" id="gender" name="gender" value="male" checked="checked">Male
<input type="radio" id="gender" name="gender" value="female">Female
</p>
<p>Weight: <input type="number" name="weight" id="weight" size="10" maxlength="6" onkeypress="if(this.value.length > 5) return false;"> kg</p>
<p>Height: <input type="number" name="height" id="height" size="10" maxlength="6" onkeypress="if(this.value.length > 5) return false;"> cm</p>
<p>Age: <input type="number" name="age" id="age" size="10" maxlength="3" onkeypress="if(this.value.length > 2) return false;"></p>
<button type="button" id="calculate">Calculate</button>
<button type="button" id="clear" onclick="clearForm()">Clear</button><br><br>
<div class="row-result-tab" id="showResult" style="display:none;">
<label>BMR = <span id="result"></span> calories/day</label>
</div>
</form>
I took some time to improve your code. As given in other answers already. You need to set the display of your result html back to none.
window.onload = function BMR() {
// Init
var gender = document.getElementById('gender');
var weight = document.getElementById('weight');
var height = document.getElementById('height');
var age = document.getElementById('age');
var calculate = document.getElementById('calculate');
// Click handler
calculate.addEventListener('click', toBmr);
function toBmr() {
// Init
// Very good practice to first declare your vars
// However include result as well here
// Remove select because it's not doing anything
var result = "";
var penalty = 0;
if (gender.value && weight.value && height.value && age.value && gender.checked) {
// When you have duplicate code, check the difference!
// Only the penalty given at the end is different!
if (gender.value == 'male') {
penalty = 5;
} else {
penalty = -161;
}
// Now we calculate with one formula
result = (10 * weight.value) + (6.25 * height.value) - (5 * age.value) + penalty;
// Add to html
document.getElementById('result').innerHTML = Number(result).toFixed(2);
document.getElementById('showResult').style.display = "block";
}
};
};
function clearForm() {
// This resets the form fields
document.getElementById("do-form").reset();
// This remove result again
document.getElementById('showResult').style.display = "none";
}
<form name="do-form" id="do-form">
<p>BMR Calculator</p>
<p>Gender:
<input type="radio" id="gender" name="gender" value="male" checked="checked">Male
<input type="radio" id="gender" name="gender" value="female">Female
</p>
<p>Weight: <input type="number" name="weight" id="weight" size="10" maxlength="6" onkeypress="if(this.value.length > 5) return false;"> kg</p>
<p>Height: <input type="number" name="height" id="height" size="10" maxlength="6" onkeypress="if(this.value.length > 5) return false;"> cm</p>
<p>Age: <input type="number" name="age" id="age" size="10" maxlength="3" onkeypress="if(this.value.length > 2) return false;"></p>
<button type="button" id="calculate">Calculate</button>
<button type="button" id="clear" onclick="clearForm()">Clear</button><br><br>
<div class="row-result-tab" id="showResult" style="display:none;">
<label>BMR = <span id="result"></span> calories/day</label>
</div>
</form>
I am so lost as to why this is not working properly, as it is on similar previous code. This is for field personnel, a cheat Sheet to simply enter values and get a fast answer (calculation). They enter the value of Num5/6/7 code multiplies 3 values one hidden then adds the last value together and upon click button the result is shown.
Here is my code (taken from copy/paste of a working conversion).
<div class="containerHydro">
<p>
<label >Fluid Column Length</label>
<input type="number" id="num5">
<label >Fluid Weight</label>
<input type="number" id="num6">
<label >Well Head Pressure</label>
<input type="number" id="num7">
<p>
<input type="button" value="Sum" onclick="calculate()"/>
</p>
<p id="total1"></p>
</div>
The Function also copy/paste of multiply two int then divide by hidden (which works BTW)
function calculate() {
var numFive = document.getElementById('num5').value;
var numSix = document.getElementById('num6').value;
var numSvn = document.getElementById('num7').value;
var total1 = parseInt(numFive) * parseInt(numSix) * 0.052 + parseInt('numSvn');
var p =document.getElementById('total1');
p.innerHTML += total1;
}
Here is the same idea which works fine-
Code-
<div class="container7">
<p>
<label id="H2S Percent">H2S Percentage</label>
<input id="num3" type="number" name="num3" placeholder="H2S Percent">
<label id="H2S Percent">WHP</label>
<input id="num4" type="number" name="num4"placeholder="Well Head Pressure" > <br>
</p>
<input type="button" value="H2S Partial Pressure" onclick="math()"/>
<p id="result"></p>
</div>
Function
function math() {
var numThree = document.getElementById('num3').value;
var numFour = document.getElementById('num4').value;
var result = parseInt(numThree) * parseInt(numFour) / 1000000;
var p = document.getElementById('result');
p.innerHTML += result;
}
function calculate() {
var numFive = document.getElementById('num5').value;
var numSix = document.getElementById('num6').value;
var numSvn = document.getElementById('num7').value;
var total1 = parseInt(numFive) * parseInt(numSix) * 0.052 + parseInt(numSvn);
var p = document.getElementById('total1');
p.innerHTML += total1;
}
input {
display: block;
}
<div class="containerHydro">
<p>
<label>Fluid Column Length</label>
<input type="number" id="num5">
<label>Fluid Weight</label>
<input type="number" id="num6">
<label>Well Head Pressure</label>
<input type="number" id="num7">
<p>
<input type="button" value="Sum" onclick="calculate()" />
</p>
<p id="total1"></p>
</div>
I'm writing a code that display content in text field on button submit click, but the code below is not working
<script>
function myFunction() {
var x = document.getElementById("cost").value;
if (document.getElementById("cost").value;) {
var netprofit = x-(16/100*x);
document.getElementById("net").value = +netprofit;
else if (document.getElementById("cost").value;) {
var commission = netprofit * 35/100;
document.getElementById("comm").value = +commission;
}
}
}
</script>
<form action="" method="POST">
<input type="text" id="cost" placeholder="kindly enter the cost value of project"><br><br>
<input type="text" name="" id="net" readonly="readonly"><br><br>
<input type="text" name="" id="comm" readonly="readonly"><br><br>
<input type="submit" value="Calculate" onclick="myFunction()">
</form>
I expect result to display in an input text onClicking button
As Harpel pointed out, you have to prevent the form from submitting. This is default behavior for forms that contain a input of type submit. I'd also suggest reorganizing your code a bit (vars for each input you selecting, etc). Something like the below:
<script>
function myFunction(event) {
event.preventDefault();
var costInput = document.getElementById("cost");
var netInput = document.getElementById("net");
var commInput = document.getElementById("comm");
if (costInput.value) {
var netprofit = costInput.value - (16/100 * costInput.value);
netInput.value = netprofit;
} else if (costInput.value) {
var commission = netprofit * 35/100;
commInput.value = commission;
}
}
</script>
<form action="" method="POST">
<input type="text" id="cost" placeholder="kindly enter the cost value of project"><br><br>
<input type="text" name="" id="net" readonly="readonly"><br><br>
<input type="text" name="" id="comm" readonly="readonly"><br><br>
<input type="submit" value="Calculate" onclick="myFunction(event)">
</form>
One additional thing; I'm not sure what the if statement is supposed to be checking, as it seems to be checking the same condition. If that's the case, you can just place both calculations for the input values into one if check like:
if (costInput.value) {
var netprofit = costInput.value - (16/100 * costInput.value);
netInput.value = netprofit;
var commission = netprofit * 35/100;
commInput.value = commission;
}
Your input type is submit. So it will always submit form and reload the page. You can do in function like
"return false" from your function,
event.preventDefault() add in your function //it will avoid the default behavior (in your case submit form).
Or use button in your HTML in place of ("input" with type "submit").
Here is working snippet, but i don't know why you are writing same condition in "if" and "else if"
function myFunction(e) {
e.preventDefault();
var cost = document.getElementById("cost").value;
if (cost) {
cost = +cost;
var netprofit = cost - (16 / 100 * cost);
var commission = netprofit * 35 / 100;
document.getElementById("net").value = +netprofit;
document.getElementById("comm").value = +commission;
}
}
<form action="" method="POST">
<input type="text" id="cost" placeholder="kindly enter the cost value of project"><br><br>
<input type="text" name="" id="net" readonly="readonly"><br><br>
<input type="text" name="" id="comm" readonly="readonly"><br><br>
<input type="submit" value="Calculate" onclick='myFunction(event)'>
</form>
<form action="" method="POST">
<input type="text" id="cost" placeholder="kindly enter the cost value of project"><br><br>
<input type="text" name="" id="net" readonly="readonly"><br><br>
<input type="text" name="" id="comm" readonly="readonly"><br><br>
<input type="button" value="Calculate" onclick="myFunction()">
</form>
<script>
function myFunction() {
var x = document.getElementById("cost").value;
if (document.getElementById("cost").value) {
var netprofit = x - (16 / 100 * x);
document.getElementById("net").value = +netprofit;
}
else if (document.getElementById("cost").value) {
var commission = netprofit * 35 / 100;
document.getElementById("comm").value = +commission;
}
}
</script>
Output
I'm exercising in calculations with variables using javascript and i can't figure out how to use superscripts in variables. With some help Javascript calculations holding variables i learned how to do calculations in general but my new question is how to use superscripts?
<form name="Calcultor" Method="Get" id='form1'>First Number:
<input type="text" name="first" size="35" id="first">+ Second Number:
<input type="text" name="second" size="35" id="second">
<br>Answer:
<input type="text" name="ans" size="35" id="ans" />
<input type="text" name="ans2" size="35" id="ans2" />
<button type="button" onclick="Calculate();">Calculate</button>
</form>
<script>
function Calculate() {
var first = document.getElementById('first').value;
var second = document.getElementById('second').value;
var ans = document.getElementById('ans').value;
var ans2 = document.getElementById('ans2').value;
document.getElementById('ans').value = parseInt(first) + parseInt(second);
document.getElementById('ans2').value = 1.112 - 0.00043499 * parseInt(document.getElementById('ans').value)/*insert ans into a parenthensis*/ + 0.00000055 * parseInt(document.getElementById('ans').value)/*insert ans into a parenthensis and ^2 outside the parenthesis*/ - 0.00028826;
}
</script>
Thanks in advance
There is a function in javascript Math.pow();
Math.pow(2,4) gives you 2^4 = 16.
Math.pow(2,4);
>16
Math.pow(2,4.1);
>17.148375400580687
<form name="Calcultor" Method="Get" id='form1'>First Number:
<input type="text" name="first" size="35" id="first">+ Second Number:
<input type="text" name="second" size="35" id="second">
<br>Answer:
<input type="text" name="ans" size="35" id="ans" />
<input type="text" name="ans2" size="35" id="ans2" />
<button type="button" onclick="Calculate();">Calculate</button>
</form>
<script>
function Calculate() {
var first = document.getElementById('first').value;
var second = document.getElementById('second').value;
var ans = document.getElementById('ans').value;
var ans2 = document.getElementById('ans2').value;
document.getElementById('ans').value = parseInt(first) + parseInt(second);
document.getElementById('ans2').value = 1.112 - 0.00043499 * parseInt(document.getElementById('ans').value) + 0.00000055 * Math.pow(parseInt(document.getElementById('ans').value), 2) - 0.00028826;
}
</script>
Updated Snippet according to answers works now!
Updated code. calculate() still not working. The monthly payment amount is ultimately not being passed to the "total" id box. Does anyone see what the underlying problem is here? My syntax seems to be correct, I believe there may be a problem with my specification of where each variable is applied in the code.
I am having problems getting the function calculate() to pass the correct result in "total." Any possible solutions? The action of clicking the calculate button should display the total, but is displaying nothing at all, as if the button does not activate the calculate function at all.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function calculate() {
var P = document.getElementById("price").value;
var D = document.getElementById("DP").value;
var R = document.getElementById("R").value;
var N = document.getElementById("N").value;
var i = (R / 1200);
var n = (N * 12);
var m = ((P - D) * i * Math.pow(1 + i,n)) / (Math.pow(1 + i,n) - 1);
var result = document.getElementById('total');
result.value = m;}
</script>
</head>
<div align="center">
<hr>
<form name id="Main">
<input type="number" id="price" placeholder="Price of the Car"/>
<br>
<br>
<input type="number" id="DP" placeholder="Down Payment"/>
<br>
<br>
<input type="number" id="R" placeholder="Annual % Rate"/>
<br>
<br>
<input type="number" id="N" placeholder="# of Years Loaned"/>
<br>
<br>
<input type="button" id="calculate" value="Calculate" onclick="javascript:calculate();"/>
<br>
<br>
<input type="number" id="total" placeholder="Total Cost..." readonly=""/>
<br>
<br>
<input type="reset" value="Reset">
</form>
<hr>
</div>
</html>
Use Math.pow() function instead. The ^ operator is not for mathematical power operations (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Bitwise_XOR and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/pow).
Also, It's result.value = m, not the other way around :)
Also 2: R and M seem undefined to me, you have to initialize those variables with something, like you did with P and D.
Also 3: use chrome dev tools or anything like that. It will make your life much easier. Remember, javascript doesn't mean "no IDE" :D
Unfortunately, your original code will never work, as it has too many errors.
Here is the corrected fiddle for you, please, have a look:
http://jsfiddle.net/q330fqw8/
function calculate() {
var P = document.getElementById("price").value;
var D = document.getElementById("DP").value;
var R = document.getElementById("R").value;
var N = document.getElementById("N").value;
var i = (R / 1200);
var n = (N * 12);
var m = ((P - D) * i * Math.pow(1 + i,n)) / (Math.pow(1 + i,n) - 1);
var result = document.getElementById('total');
result.value = m;
}
I removed id="calculate" in HTML, because of this: Why JS function name conflicts with element ID?
In Javascript, the 4 variables P,D,R,N should be set properly. Finally, this m.value = result; -> result.value = m;
but I guess, you've already corrected some errors in the question. I worked with your original code.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function calculate() {
var P = document.getElementById("price").value;
var D = document.getElementById("DP").value;
var R = document.getElementById("R").value;
var N = document.getElementById("N").value;
var i = (R / 1200);
var n = (N * 12);
var m = ((P - D) * i * Math.pow(1 + i,n)) / (Math.pow(1 + i,n) - 1);
var result = document.getElementById('total');
result.value = m;}
</script>
</head>
<div align="center">
<hr/>
<form id="Main">
<input type="number" id="price" placeholder="Price of the Car" />
<br />
<br/>
<input type="number" id="DP" placeholder="Down Payment" />
<br/>
<br/>
<input type="number" id="R" placeholder="Annual % Rate" />
<br/>
<br/>
<input type="number" id="N" placeholder="# of Years Loaned" />
<br/>
<br/>
<input type="button" value="Calculate Monthly Payment" onclick="calculate();" />
<br/>
<br/>
Total Monthly Payment:<input type="number" id="total" placeholder="Total Cost..." readonly="" />
<br/>
<br/>
<input type="reset" value="Reset" />
</form>
<hr/>
</div>