limit digits in var multiplication total - javascript

I have this:
var ivu = (total3);
document.getElementById("project_pay_total_field4").value = "$" + total3 * 0.07 ;
The multiplication produces this:
$10.080000000000002
--Its too long and when done in regular calculator it only says 10.08; how can i fix that?
Here is the function:
<script type = "text/javascript">
function project_pay_detail() {
var rate = document.getElementById("project_rate_field").value;
var time = document.getElementById("project_time_field").value;
var total1 = (rate * time);
document.getElementById("project_pay_total_field").value = "$" + total1 + ".00";
var rate = document.getElementById("project_rate_field2").value;
var time = document.getElementById("project_time_field2").value;
var total2 = (rate * time);
document.getElementById("project_pay_total_field2").value = "$" + total2 + ".00";
var total3 = (total1 + total2);
document.getElementById("project_pay_total_field3").value = "$" + total3 + ".00" ;
var ivu = (total3);
document.getElementById("project_pay_total_field4").value = "$" + total3 * 0.07 ;
}
</script>
Heres is the form
<div id="project_pay">Pay Rate<input type="text" name="project_rate_field" id="project_rate_field" class="field" value="" /></div>
<div id="project_pay">Total Hours<input type="text" name="project_time_field" id="project_time_field" class="field" value="" /></div>
<div id="project_pay">Project Total<input type="text" name="project_pay_total_field" id="project_pay_total_field" class="field" readonly="readonly" value="" /></div>
<input name="project_pay_details_calculate" type="button" value="Calculate1" onClick="project_pay_detail()" /></input>
<br>
<div id="project_pay">Pay Rate2<input type="text" name="project_rate_field2" id="project_rate_field2" class="field" value="" /></div>
<div id="project_pay">Total Hours2<input type="text" name="project_time_field2" id="project_time_field2" class="field" value="" /></div>
<div id="project_pay">Project Total2<input type="text" name="project_pay_total_field2" id="project_pay_total_field2" class="field" title="0.00" readonly="readonly" value="" /></div>
<input name="project_pay_details_refresh" type="button" value="Calculate2" onClick="project_pay_detail()" /></input>
<div id="project_pay">Total<input type="text" name="project_pay_total_field3" id="project_pay_total_field3" class="field" title="0.00" readonly="readonly" value="" /></div>
<div id="project_pay">Ivu<input type="text" name="project_pay_total_field4" id="project_pay_total_field4" class="field" title="0.00" readonly="readonly" value="" /></div>
</div>

try using: number.toFixed(x)
var result = (total3 * 0.07);
document.getElementById("project_pay_total_field4").value = "$" + result.toFixed(2);
http://www.w3schools.com/jsref/jsref_tofixed.asp

total3 = Math.round(total3 * 100) / 100;

Related

Don't calculate if a field is empty (Js calculator)

I'm trying to limit a calculation only when a field is blank. I have many other fields that are calculated simultaneously, I would like to limit the calculation to only the fields that have not been filled.
I don't know JS very well, so I hope to be able to find help here ... Thanks for any answers, I leave more info below.
Basically everything works fine. However, when the bodyfat field is empty, the calculation for BMR and TDEE Katch McArdle and Cunningham Formula is performed.
What I am trying to do is to calculate the McArdle and Cunningham Formula fields only when the Bodyfat field contains values.
calculate = function()
{
var weight = document.getElementById('weight').value;
var height = document.getElementById('height').value;
var age = document.getElementById('age').value;
var bodyfat = document.getElementById('bodyfat').value / 100;
var select_lvl = document.querySelector('#a_level option:checked').value;
//Sex Selection Hide-Show Div//
var sex = document.querySelector('input[name="radios"]:checked').value;
document.getElementById('bmr-sexuomo').hidden = sex !== 'Male';
document.getElementById('bmr-sexdonna').hidden = sex !== 'Female';
document.getElementById('MifflinMale').hidden = sex !== 'Male';
document.getElementById('MifflinFemale').hidden = sex !== 'Female';
var bmr_mifflin_man = (10*weight) + (6.25*height) - (5*age) + 5;
document.getElementById('bmr_mifflin_man').value = bmr_mifflin_man.toLocaleString('it-IT', {maximumFractionDigits: 0}) + " Kcal";
var tdee_mifflin_man = (bmr_mifflin_man*select_lvl);
document.getElementById('tdee_mifflin_man').value = tdee_mifflin_man.toLocaleString('it-IT', {maximumFractionDigits: 0}) + " Kcal";
var bmr_mifflin_woman = (10*weight) + (6.25*height) - (5*age) - 161;
document.getElementById('bmr_mifflin_woman').value = bmr_mifflin_woman.toLocaleString('it-IT', {maximumFractionDigits: 0}) + " Kcal";
var tdee_mifflin_woman = (bmr_mifflin_woman*select_lvl);
document.getElementById('tdee_mifflin_woman').value = tdee_mifflin_woman.toLocaleString('it-IT', {maximumFractionDigits: 0}) + " Kcal";
//Result BMR Katch Mc Ardle Formula
var bmr_katch = (370 + ( 21.6 * ( weight * ( 1 - bodyfat ))));
document.getElementById('bmr_katch').value = bmr_katch.toLocaleString('it-IT', {maximumFractionDigits: 0}) + " Kcal";
//Result TDEE Katch Mc Ardle Formula
var tdee_katch = (bmr_katch*select_lvl);
document.getElementById('tdee_katch').value = bmr_katch.toLocaleString('it-IT', {maximumFractionDigits: 0}) + " Kcal";
//Result BMR Cunningham Formula
var bmr_cunningham = (500 + ( 22 * ( weight * ( 1 - bodyfat ))));
document.getElementById('bmr_cunningham').value = bmr_cunningham.toLocaleString('it-IT', {maximumFractionDigits: 0}) + " Kcal";
//Result TDEE Cunningham Formula
var tdee_cunningham = (bmr_cunningham*select_lvl);
document.getElementById('tdee_cunningham').value = bmr_cunningham.toLocaleString('it-IT', {maximumFractionDigits: 0}) + " Kcal";
//This is Activity Level Radio Selection//
var leggeros = document.getElementById('leggeros').value * 1.2;
var attivos = document.getElementById('attivos').value * 1.375;
var allenatos = document.getElementById('allenatos').value * 1.55;
var Mattivos = document.getElementById('Mattivos').value * 1.75;
var Eattivos = document.getElementById('Eattivos').value * 1.9;
}
//Reset Function
function resetFields() {
document.getElementById("bmrcalc").reset();
document.getElementById('bmr_katch').value = ''
document.getElementById('bmr_mifflin_man').value = ''
var ele = document.getElementsByName("radiosa");
for(var i=0;i<ele.length;i++)
ele[i].checked = false;
}
https://jsfiddle.net/snake93/4n9dgbfw/3/
I have added a if condition for checking body fat Now it will works fine.
calculate = function()
{
var weight = document.getElementById('weight').value || 0;
var height = document.getElementById('height').value || 0;
var age = document.getElementById('age').value || 0;
var bodyfat = document.getElementById('bodyfat').value / 100;
var select_lvl = document.querySelector('#a_level option:checked').value;
//Sex Selection Hide-Show Div//
var sex = document.querySelector('input[name="radios"]:checked').value || "Male" ;
document.getElementById('bmr-sexuomo').hidden = sex !== 'Male';
document.getElementById('bmr-sexdonna').hidden = sex !== 'Female';
document.getElementById('MifflinMale').hidden = sex !== 'Male';
document.getElementById('MifflinFemale').hidden = sex !== 'Female';
if(bodyfat!=""){
var bmr_mifflin_man = (10*weight) + (6.25*height) - (5*age) + 5;
document.getElementById('bmr_mifflin_man').value = bmr_mifflin_man.toLocaleString('it-IT', {maximumFractionDigits: 0}) + " Kcal";
var tdee_mifflin_man = (bmr_mifflin_man*select_lvl);
document.getElementById('tdee_mifflin_man').value = tdee_mifflin_man.toLocaleString('it-IT', {maximumFractionDigits: 0}) + " Kcal";
var bmr_mifflin_woman = (10*weight) + (6.25*height) - (5*age) - 161;
document.getElementById('bmr_mifflin_woman').value = bmr_mifflin_woman.toLocaleString('it-IT', {maximumFractionDigits: 0}) + " Kcal";
var tdee_mifflin_woman = (bmr_mifflin_woman*select_lvl);
document.getElementById('tdee_mifflin_woman').value = tdee_mifflin_woman.toLocaleString('it-IT', {maximumFractionDigits: 0}) + " Kcal";
//Result BMR Katch Mc Ardle Formula
var bmr_katch = (370 + ( 21.6 * ( weight * ( 1 - bodyfat ))));
document.getElementById('bmr_katch').value = bmr_katch.toLocaleString('it-IT', {maximumFractionDigits: 0}) + " Kcal";
//Result TDEE Katch Mc Ardle Formula
var tdee_katch = (bmr_katch*select_lvl);
document.getElementById('tdee_katch').value = bmr_katch.toLocaleString('it-IT', {maximumFractionDigits: 0}) + " Kcal";
//Result BMR Cunningham Formula
var bmr_cunningham = (500 + ( 22 * ( weight * ( 1 - bodyfat ))));
document.getElementById('bmr_cunningham').value = bmr_cunningham.toLocaleString('it-IT', {maximumFractionDigits: 0}) + " Kcal";
//Result TDEE Cunningham Formula
var tdee_cunningham = (bmr_cunningham*select_lvl);
document.getElementById('tdee_cunningham').value = bmr_cunningham.toLocaleString('it-IT', {maximumFractionDigits: 0}) + " Kcal";
}
//This is Activity Level Radio Selection//
var leggeros = document.getElementById('leggeros').value * 1.2;
var attivos = document.getElementById('attivos').value * 1.375;
var allenatos = document.getElementById('allenatos').value * 1.55;
var Mattivos = document.getElementById('Mattivos').value * 1.75;
var Eattivos = document.getElementById('Eattivos').value * 1.9;
}
//Reset Function
function resetFields() {
document.getElementById("bmrcalc").reset();
document.getElementById('bmr_katch').value = ''
document.getElementById('bmr_mifflin_man').value = ''
var ele = document.getElementsByName("radiosa");
for(var i=0;i<ele.length;i++)
ele[i].checked = false;
}
.mts-field {
width:100%;
text-align: right;
border-bottom: 2px solid #DCDCDE !important;
background: #fff;
}
<label id="prov" class="mts-label">Peso</label>
<input oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);" type="number" class="mts-field" maxlength="3" id="weight" name="weight1" placeholder="es: 70Kg" form="bmrcalc" required/>
<label class="mts-label">Altezza</label>
<input oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);" type="number" class="mts-field" maxlength="3" id="height" name="height1" placeholder="es: 170cm" form="bmrcalc" required/>
<label class="mts-label">Età</label>
<input oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);" type="number" class="mts-field" maxlength="2" id="age" name="age1" placeholder="es: 25 anni" form="bmrcalc" required/>
<label class="mts-label">Bodyfat in %</label>
<input oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);" type="number" class="mts-field" maxlength="2" id="bodyfat" name"bodyfat1" placeholder="es: 15%" form="bmrcalc" />
<div class="mts-label">Sesso</div>
<!--Radio Button Sex-->
<div class="mts-radio-button">
<input type="radio" id="sexuomo" name="radios" value="Male" form="bmrcalc" required>
<label class="mts-label-radio" for="sexuomo">Uomo</label>
</div>
<div class="mts-radio-button1">
<input type="radio" id="sexdonna" name="radios" value="Female" form="bmrcalc" required>
<label class="mts-label-radio" for="sexdonna">Donna</label>
</div>
<!--Select Activity Level-->
<div class="container_level">
<select class="a_level" id="a_level" name="activ_level">
<option value="0">Stile di vita / Attività fisica</option>
<option id="leggeros" name="radiosa" value="1.2">Sedentario (1.2)</option>
<option id="attivos" name="radiosa" value="1.375">Leggero (1.375) </option>
<option id="allenatos" name="radiosa" value="1.55">Moderato (1.55)</option>
<option id="Mattivos" name="radiosa" value="1.75">Attivo (1.75)</option>
<option id="Eattivos" name="radiosa" value="1.9">Estremamente attivo (1.9)</option>
</select>
</div>
<!---BMR Mifflin StJeor Result Field--->
<br>
<label class="mts-label">BMR Mifflin St Jeor Formula</label><br>
<div id="bmr-sexuomo">
<label class="mts-label">Male</label><br>
<input type="text" class="mts-field" id="bmr_mifflin_man" name="bmr_mifflin_man"
placeholder="0.000,0 Kcal" min="1" readonly/>
</div>
<br>
<div id="bmr-sexdonna" hidden>
<label class="mts-label">Female</label><br>
<input type="text" class="mts-field" id="bmr_mifflin_woman" name="bmr_mifflin_woman"
placeholder="0.000,0 Kcal" min="1" readonly/>
</div>
<!---TDEE Mifflin StJeor Result Field--->
<br>
<label class="mts-label">TDEE Mifflin St Jeor Formula</label><br>
<div id="MifflinMale">
<label class="mts-label">Male</label><br>
<input type="text" class="mts-field" id="tdee_mifflin_man" name="tdee_mifflin_man"
placeholder="0.000,0 Kcal Uomo" min="1" readonly/>
</div>
<br>
<div id="MifflinFemale" hidden>
<label class="mts-label">Female</label><br>
<input type="text" class="mts-field" id="tdee_mifflin_woman" name="tdee_mifflin_woman"
placeholder="0.000,0 Kcal donna" min="1" readonly/>
</div>
<!---BMR Katch McArdle Formula--->
<br>
<label class="mts-label">BMR Katch McArdle Formula</label>
<div id="Ktch">
<input type="text" class="mts-field" id="bmr_katch" name="bmr_katch"
placeholder="0.000,0 Kcal" maxlength="6" readonly/>
</div>
<!---TDEE Katch McArdle Formula--->
<br>
<label class="mts-label">TDEE Katch McArdle Formula</label>
<div id="Ktch1">
<input type="text" class="mts-field" id="tdee_katch" name="tdee_katch"
placeholder="0.000,0 Kcal" maxlength="6" readonly/>
</div>
<!---BMR Cunningham Formula--->
<br>
<label class="mts-label">BMR Cunningham Formula</label>
<div id="Cunningham">
<input type="text" class="mts-field" id="bmr_cunningham" name="bmr_cunningham"
placeholder="0.000,0 Kcal" maxlength="6" readonly/>
</div>
<!---TDEE Cunningham Formula--->
<br>
<label class="mts-label">TDEE Cunningham Formula</label>
<div id="Cunninghams">
<input type="text" class="mts-field" id="tdee_cunningham" name="tdee_cunningham"
placeholder="0.000,0 Kcal" maxlength="6" readonly/>
</div>
<!---Calc & Reset Button--->
<br>
<form action="" id="bmrcalc">
</form>
<button name="calculate" onclick="calculate()">Calculate</button>
<button id="reset" onclick="resetFields()">Reset</button>
You need to reverse engineer it (think opposite of what you want). For example, think that calling a function when there is something in the textbox is the same as not calling a function when there isn't something in the textbox. So now you have your answer! You just need to add this in your code:
if (document.getElementById('bodyfat').value==""){
preventDefault();
alert("You need to enter something in the textbox first");
}
Thinking like this can help save a lot of time. You didn't need to know anything about Javascript for this, right?

Why does form not reset (all fields and div of result) after click clear?

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>

HTML JavaScript random number select

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>

Remove decimal in JavaScript for automatically result

I made a calculator with JavaScript for calculate result automatically. It's work but I can't remove decimal.
Here is my code:
$(document).ready(function() {
$(".input").keyup(function() {
var val1 = +$(".value1").val();
var val2 = +$(".value2").val();
var val3 = +$(".value3").val();
var val4 = +$(".value4").val();
var val5 = (".result");
var decval5 = (val5);
$(decval5).val(((((val1 / 8) + val2) / 16) + val3) * val4);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<div style="border: 1px solid #D3D3D3;background:#fff;">
<div style="padding:10px 0px 10px 10px;">
<div style="font-size:20px;"></div>
<br>
<center>
input1
<input type="text" class="input value3">input2
<input type="text" class="input value2"> input3
<input type="text" class="input value1"> input4
<input type="text" class="input value4"> = result
<input type="text" disabled="disabled" class="result">
</center>
</div>
<br>
</div>
You can use Math.round():
$(document).ready(function() {
$(".input").keyup(function() {
var val1 = +$(".value1").val();
var val2 = +$(".value2").val();
var val3 = +$(".value3").val();
var val4 = +$(".value4").val();
var val5 = (".result");
var decval5 = (val5);
$(decval5).val(Math.round(((((val1 / 8) + val2) / 16) + val3) * val4));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="border: 1px solid #D3D3D3;background:#fff;">
<div style="padding:10px 0px 10px 10px;">
<div style="font-size:20px;"></div>
<br>
<center>
input1
<input type="text" class="input value3">input2
<input type="text" class="input value2"> input3
<input type="text" class="input value1"> input4
<input type="text" class="input value4"> = result
<input type="text" disabled="disabled" class="result">
</center>
</div>
<br>
</div>
try,
$(decval5).val(Math.round(((((val1 / 8) + val2) / 16) + val3) * val4));
You can round the answer up or down or just truncate it:
$(document).ready(function() {
$(".input").keyup(function() {
var val1 = +$(".value1").val();
var val2 = +$(".value2").val();
var val3 = +$(".value3").val();
var val4 = +$(".value4").val();
var val5 = (".result");
var decval5 = (val5);
$(decval5).val(((((val1 / 8) + val2) / 16) + val3) * val4);
// Round Up:
console.log(Math.ceil(parseFloat($(decval5).val())));
// Round Down:
console.log(Math.floor(parseFloat($(decval5).val())));
// Truncate:
console.log(parseFloat($(decval5).val()).toFixed(0));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<div style="border: 1px solid #D3D3D3;background:#fff;">
<div style="padding:10px 0px 10px 10px;">
<div style="font-size:20px;"></div>
<br>
<center>
input1
<input type="text" class="input value3">input2
<input type="text" class="input value2"> input3
<input type="text" class="input value1"> input4
<input type="text" class="input value4"> = result
<input type="text" disabled="disabled" class="result">
</center>
</div>
<br>
</div>

Getting wrong calculation in javascript

I am having table below.. but Getting wrong calculation in javascript..
<script>
function getPrice(tRate, tMaking, tHandeling, tPrice, tVat, tQuantity, tTotal) {
var obj_tRate = document.getElementById(tRate)
var obj_tMaking = document.getElementById(tMaking)
var obj_tHandeling = document.getElementById(tHandeling)
var obj_tPrice = document.getElementById(tPrice)
var obj_tVat = document.getElementById(tVat)
var obj_tTotal = document.getElementById(tTotal)
var obj_tQuantity = document.getElementById(tQuantity)
if (obj_tRate.value != "" && obj_tMaking.value != "" && obj_tHandeling.value != "") {
obj_tPrice.value = parseFloat(obj_tRate.value) + parseFloat(obj_tMaking.value) + parseFloat(obj_tHandeling.value);
console.log(obj_tPrice.value)
obj_tVat.value = parseFloat(obj_tPrice.value * (1 / 100));
console.log(obj_tVat.value)
obj_tTotal.value = parseFloat(obj_tVat.value + (obj_tPrice.value * obj_tQuantity.value));
console.log(obj_tTotal.value)
}
else {
obj_tPrice.value = "";
}
}
</script>
</head>
<body>
<table>
<tr>
<td>
<input name="grdView$ctl08$txtWaight_F" type="text" id="grdView_ctl08_txtWaight_F" class="classWaight" style="width:60px;" />
</td><td>
<input name="grdView$ctl08$txtQuantity_F" type="text" maxlength="20" id="grdView_ctl08_txtQuantity_F" class="classQuantity" onchange="javascript:return getPrice('grdView_ctl08_txtRate_F','grdView_ctl08_txtMaking_F','grdView_ctl08_txtHandeling_F','grdView_ctl08_txtPrice_F','grdView_ctl08_txtvat_F','grdView_ctl08_txtQuantity_F','grdView_ctl08_txtTotal_F');" style="width:60px;" />
</td><td>
<input name="grdView$ctl08$txtRate_F" type="text" maxlength="8" id="grdView_ctl08_txtRate_F" class="classRate" onchange="javascript:return getPrice('grdView_ctl08_txtRate_F','grdView_ctl08_txtMaking_F','grdView_ctl08_txtHandeling_F','grdView_ctl08_txtPrice_F','grdView_ctl08_txtvat_F','grdView_ctl08_txtQuantity_F','grdView_ctl08_txtTotal_F');" style="width:60px;" />
</td><td>
<input name="grdView$ctl08$txtMaking_F" type="text" id="grdView_ctl08_txtMaking_F" class="classMaking" onchange="javascript:return getPrice('grdView_ctl08_txtRate_F','grdView_ctl08_txtMaking_F','grdView_ctl08_txtHandeling_F','grdView_ctl08_txtPrice_F','grdView_ctl08_txtvat_F','grdView_ctl08_txtQuantity_F','grdView_ctl08_txtTotal_F');" style="width:60px;" />
</td><td>
<input name="grdView$ctl08$txtHandeling_F" type="text" id="grdView_ctl08_txtHandeling_F" class="classHandling" onchange="javascript:return getPrice('grdView_ctl08_txtRate_F','grdView_ctl08_txtMaking_F','grdView_ctl08_txtHandeling_F','grdView_ctl08_txtPrice_F','grdView_ctl08_txtvat_F','grdView_ctl08_txtQuantity_F','grdView_ctl08_txtTotal_F');" style="width:60px;" />
</td><td>
<input name="grdView$ctl08$txtPrice_F" type="text" id="grdView_ctl08_txtPrice_F" class="classPrice" style="width:60px;" />
</td><td>
<input name="grdView$ctl08$txtvat_F" type="text" id="grdView_ctl08_txtvat_F" class="classVat" style="width:60px;" />
</td><td>
<input name="grdView$ctl08$txtTotal_F" type="text" id="grdView_ctl08_txtTotal_F" class="classTotal" style="width:100px;" />
</td><td>
<input name="grdView$ctl08$txtSerial_F" type="text" id="grdView_ctl08_txtSerial_F" class="classSerial" />
</td>
</tr>
</table>
</body>
Use parseFloat on the operands, not on the result of the computation.
For example, replace
obj_tTotal.value = parseFloat(obj_tVat.value + (obj_tPrice.value * obj_tQuantity.value));
with
var tPrice = parseFloat(obj_tPrice.value);
var tQuantity = parseFloat(obj_tQuantity.value);
obj_tTotal.value = tPrice + tPrice * tQuantity;
When you add, like you did, a string and a number, you do a string concatenation.
For example
"1000" + "5" * "100"
gives
"1000" + 500
which is
"1000500"
At this point, it's too late to call parseFloat.

Categories

Resources