this is my html input field
<input type="number" id="t1">
<br />
<button type="button" onclick="getvalue()">calculate</button>
<br />
<div id="l1">change<div>
this is my script
<script>
function getvalue() {
var l = document.getElementById('l1');
var c = document.getElementById('t1').value;
var lc = c + 200;
var tax = 2.1;
var tot = lc * tax;
l.innerHTML=tot;
}
</script>
and in text box i enter 10 so result is 441 this is the calculation 10+200 = 210
then 210*2.1 = 441
but in text box i enter 10 and click button i got 21420
the problem is var lc = c + 200; this is not calculate correct here its work 10200
and i try this method also var x = 200; var lc = c + x; this is also i got 10200 how can i fix this?
type of value in input number is string.
var val = document.getElementById('t1').value ;
console.log( typeof val ) ;
<input type="number" id="t1">
So you must convert to number like this:
var lc = Number(c) + 200 ;
//OR
var lc = parseInt(c) + 200 ;
//OR
var lc = parseFloat(c) + 200 ;
function getvalue() {
var l = document.getElementById('l1');
var c = document.getElementById('t1').value;
var lc = Number(c) + 200;
var tax = 2.1;
var tot = lc * tax;
l.innerHTML=tot;
}
<input type="number" id="t1">
<br />
<button type="button" onclick="getvalue()">calculate</button>
<br />
<div id="l1">change <div>
Even though the type of input is number, actually the value is of type string. That's why string concatenation is happening.
You can check the type of value with typeof operator.
To perform the intended arithmetic operation, you have to convert the value to number.
Please Note: It is better to use textContent instead of innerHTML when dealing with text only content.
var c = Number(document.getElementById('t1').value);
function getvalue() {
var l = document.getElementById('l1');
var c = document.getElementById('t1').value;
console.log(typeof(c)); //string
var lc = Number(c) + 200;
var tax = 2.1;
var tot = lc * tax;
l.textContent = tot;
}
<input type="number" id="t1"> <br />
<button type="button" onclick="getvalue()">calculate</button> <br />
<div id="l1">change <div>
Related
So I have this form that is performing very basic calculations and when I submit it, it results to NaN.
The thing that is confusing me is when I do a typeof of one of the variables assigned to the value of each input, it returns "number", and yet I get NaN as a result. Can anyone tell me why or what it is I am doing wrong?
Here's my HTML:
<form name="baddiesCost">
<input type="number" placeholder="Total Caught" name="goomba" id="goomba-form">
<input type="number" placeholder="Total Caught" name="bobombs" id="bob-ombs-form">
<input type="number" placeholder="Total Caught" name="cheepCheeps" id="cheep-form">
<button id="submitForm">Submit</button>
</form>
<h1 id="total"></h1>
Here's my JavaScript:
document.baddiesCost.addEventListener("submit", function(e) {
e.preventDefault();
var goombaCaught = document.baddiesCost.goomba.value * goombaCost;
var bobombsCaught = document.baddiesCost.bobombs.value * bobombsCost;
var cheepsCaught = document.baddiesCost.cheepCheeps.value * cheepCost;
var goombaCost = 5;
var bobombsCost = 7;
var cheepCost = 11;
var showTotal = document.getElementById("total");
var total = goombaCaught + bobombsCaught + cheepsCaught;
showTotal.textContent = cheepsCaught;
console.log(bobombsCaught);
console.log(typeof bobombsCaught);
})
This statement document.baddiesCost.bobombs.value * bobombsCost; uses variable bobombsCost which is not defined at this time.
So, it is similar to: document.baddiesCost.bobombs.value * undefined; which will be NaN.
To solve this put variable inicialization before usage like in following code:
document.baddiesCost.addEventListener("submit", function(e) {
e.preventDefault();
var goombaCost = 5;
var bobombsCost = 7;
var cheepCost = 11;
var goombaCaught = document.baddiesCost.goomba.value * goombaCost;
var bobombsCaught = document.baddiesCost.bobombs.value * bobombsCost;
var cheepsCaught = document.baddiesCost.cheepCheeps.value * cheepCost;
var showTotal = document.getElementById("total");
var total = goombaCaught + bobombsCaught + cheepsCaught;
showTotal.textContent = cheepsCaught;
console.log(bobombsCaught);
console.log(typeof bobombsCaught);
})
Anyway, NaN is number type, you can refer to following post for more explaination.
EDIT2: I removed the input validations, so now values don't get corrupted.
Added more functions to onkeyup method. However, if for eg, I enter three values, for Widht, GSM and Weight, Length will be calculated but since all functions are in on key up, along with length, other values change as well.
How do I make it so that when Length is being calculated, other values don't alter?
EDIT: For eg, if value for Length, Width and GSM is provided, then value for Weight will be assigned { formula: Length * Width * GSM/3100 }
if value for Width, GSM and Weight are given, then Length should be calculated { formula: (Weight * 3100) / width * GSM }
and so on.
I have four input boxes, What I want is when the user puts in any of the three boxes the fourth value should generate automatically in the fourth box.
Right now my code works when there is a fixed box in which we have to get the fourth value
New HTML:
<!DOCTYPE html>
<html>
<head>
<title>Paper Calc 2</title>
<script type="text/javascript" src = "js/test.js"></script>
<link rel="stylesheet" type="text/css" href="css/CALC.css">
<meta charset="utf-8">
</head>
<body>
<div class="container-fluid">
<div id = "case_one" class="calcoptions sizemod">
<h5>1. To find the weight (in <b>Kilograms</b>) of a ream containing 500 sheets of a given size in <b>inches</b> and <b>Gram-Weight.</b></h5>
<br>
<div class="row">
<div class="col-md-6">
Length: <input type="number" step="0.01" name="length_in" id="length" placeholder="Length(inch)" onkeyup="fun(); fun2(); fun3();">inch
<br><br>
Width: <input type="number" step="0.01" name="width_in" id="width" placeholder="Width(inch)" onkeyup="fun(); fun2(); fun4();">inch
<br><br>
GSM: <span class="extraSpace"> </span><input type="number" step="0.01" name="length_in" id="GSM" placeholder="GSM" onkeyup="fun(); fun3(); fun4();"> <!-- <button type = "button" name = "calc2" class = 'btnclass' id="cal2" onclick="func2()"> calc2-->
</button>
<br><br>
Weight: <input type="number" step = "0.01" name="Weight_Kg" id = "weight" onkeyup="fun2(); fun3(); fun4();"> <!-- KG <button type = "button" name = "calc1" id="cal1" class = 'btnclass' onclick="func1()">
calc1 -->
</button>
<br><br>
</div>
<p id='err'></p>
</body>
</html>
New JS:
function fun()
{
var l = document.getElementById('length').value;
var w = document.getElementById('width').value;
var g = document.getElementById('GSM').value;
if (l && w && g)
{
var wt = document.getElementById('weight');
var calculate = (eval(l)*eval(w)*eval(g))/3100;
wt.value = calculate.toFixed(2);
}
};
function fun2()
{
var l = document.getElementById('length').value;
var w = document.getElementById('width').value;
var wt = document.getElementById('weight').value;
if (l && w && wt)
{
var g = document.getElementById('GSM');
var calculate = (eval(wt)*3100)/(eval(l)*eval(w));
g.value = calculate.toFixed(2);
}
};
function fun3()
{
var l = document.getElementById('length').value;
var wt = document.getElementById('weight').value;
var g = document.getElementById('GSM').value;
if (l && g && wt)
{
var w = document.getElementById('width');
var calculate = (eval(wt)*3100)/(eval(l)*eval(g));
w.value = calculate.toFixed(2);
}
};
function fun4()
{
var w = document.getElementById('width').value;
var wt = document.getElementById('weight').value;
var g = document.getElementById('GSM').value;
if (w && g && wt)
{
var l = document.getElementById('length');
var calculate = (eval(wt)*3100)/(eval(w)*eval(g));
l.value = calculate.toFixed(2);
}
};
function calculateWeightInInches() {
var Length = document.getElementById("txt_weight").value;
var width = document.getElementById("txt_width").value;
var GSM = document.getElementById("txt_GSM").value;
var calculate = (Length * width * GSM) / 3100;
var result = document.getElementById("txt_Result");
// if (Length < 0)
// {
// document.getElementById('err').innerHTML = 'Incorrect Length!';
// }
error = document.getElementById('err_1');
if (calculate < 0 || width > 300 || width < 1 || GSM < 5 || GSM > 800 || Length < 1 || Length > 99) {
result.value = 0;
error.style.display = 'block';
} else {
result.value = calculate.toFixed(2);
error.style.display = 'none';
}
}
<div class="container-fluid">
<div id="case_one" class="calcoptions sizemod">
<h5>1. To find the weight (in <b>Kilograms</b>) of a ream containing 500 sheets of a given size in <b>inches</b> and <b>Gram-Weight.</b></h5>
<br>
<div class="row">
<div class="col-md-6">
Length: <input type="number" step="0.01" name="length_in" id="txt_weight" placeholder="Length(inch)" min="1" max="99" onkeyup="calculateWeightInInches();">inch
<br><br> Width: <input type="number" step="0.01" name="width_in" id="txt_width" placeholder="Width(inch)" min="1" max='300' onkeyup="calculateWeightInInches();">inch
<br><br> GSM: <span class="extraSpace"> </span><input type="number" min="5" max="800" step="0.01" name="length_in" id="txt_GSM" placeholder="GSM" onkeyup="calculateWeightInInches();">
<br><br> Weight: <input type="number" step="0.01" name="Weight_Kg" id="txt_Result" readonly="readonly">KG
<br><br>
</div>
<div class="col-md-6">
<p id="err_1" style="display: none;">
Valid Range: <br> L = 1 to 99 inch <br> W = 1 to 99 inch <br> GSM = 5 to 800 <br><br> Formula: (Length * width * GSM) / 3100
</p>
</div>
</div>
</div>
<div id="case_two" class="calcoptions sizemod">
I am trying by putting another function in onkeyup but it ruins the code.
[because values keep changing]
Any help would be appreciated!
function calculateWeightInInches() {
var Length = document.getElementById("txt_weight").value;
var width = document.getElementById("txt_width").value;
var GSM = document.getElementById("txt_GSM").value;
var calculate = (Length * width * GSM) / 3100;
var result = document.getElementById("txt_Result");
// if (Length < 0)
// {
// document.getElementById('err').innerHTML = 'Incorrect Length!';
// }
error = document.getElementById('err_1');
if(calculate < 0 || width > 300 || width < 1 || GSM < 5 || GSM > 800 || Length < 1 || Length > 99)
{
result.value = 0;
error.style.display = 'block';
}
else
{
if(Length && width && GSM) {
var GSMElement = document.getElementById("txt_GSM");
var lengthElement = document.getElementById("txt_weight");
var widthElement = document.getElementById("txt_width");
var elementsArray = [GSMElement,widthElement,lengthElement]
elementsArray.forEach(function(ele){
ele.addEventListener('change', function() {
result.value = calculate.toFixed(2);
error.style.display = 'none';
})
})
}
}
}
I just want to get the square root of total2 .. but it won't appear in the selected box ..
here is the javascript codes.
i'll comment the html codes.
function myFunction() {
var q1 = document.getElementById("qinput1").value;
var q2 = document.getElementById("qinput2").value;
var q3 = document.getElementById("qinput3").value;
var total = parseInt(q1) + parseInt(q2) + parseInt(q3);
document.getElementById("ainput3").value=total;
var a1 = document.getElementById("ainput1").value;
var a2 = document.getElementById("ainput2").value;
//from the total we got, lets assign it a variable for further calculation
var a3 = document.getElementById("ainput3").value=total;
var total2 = parseInt(a1)*parseInt(a2)/ parseInt(a3);
document.getElementById("ansA").value = total2;
var total3 = math.sqrt(parseInt(total2));
document.getElementById("sqaureD").value = total3;
}
function myShapes() {
document.getElementById('squareA').style.display =
document.getElementById('shapes').value == 'Square' ? 'block' : 'none'
}
<form action="" id="fcalculation">
<fieldset>
<legend>Calculation of qu</legend>
<label><i>Ultimate bearing capacity</i> <b>(qu) = </b></label>
<input id="qinput1" type="text" placeholder="c'NcFcsFcdFci"/> +
<input id="qinput2" type="text" placeholder="qNqFqsFqdFqi"/> +
<input id="qinput3" type="text" placeholder="½βγNFγsFγdFγi"/>
</fieldset>
</form>
it seems that the calculation part at the very end is not working. sorry its my first time to code.
Classname is Math not math
Try replacing
var total3 = math.sqrt(parseInt(total2,10));
with
var total3 = Math.sqrt(parseInt(total2,10));
Also, looking at your markup, there are no fields with id ainput1, ainput2 and ainput3.
I have some problem to get value from input field. Some input field is a result from calculation process, such as #t1_potensi and #t2_potensi. While #aliran is the result of the overall calculation process.
This is my HTML code.
<input oninput="hitung()" name="v_potensi" id="v_potensi" type="text" placeholder="liter . . ." />
<input oninput="hitung()" name="a_potensi" id="a_potensi" type="text" placeholder="menit . . ." />
<input oninput="hitung()" name="b_potensi" id="b_potensi" type="text" placeholder="menit . . ." />
<input oninput="hitungT1()" name="kecepatan_air" id="kecepatan_air" type="text" placeholder="km/jam . . ." />
<input oninput="hitungT1()" name="jarak1" id="jarak1" type="text" placeholder="kilometer . . ." />
<input oninput="hitungT2()" name="kecepatan_back" id="kecepatan_back" type="text" placeholder="km/jam . . ." />
<input oninput="hitungT2()" name="jarak2" id="jarak2" type="text" placeholder="kilometer . . ." />
<!-- #t1_potensi = 0.65 + ((60 / #kecepatan_air) * #jarak1) -->
<input readonly="readonly" oninput="hitung()" name="t1_potensi" id="t1_potensi" type="text" placeholder="menit . . ." />
<!-- #t2_potensi = 0.65 + ((60 / #kecepatan_back) * #jarak2) -->
<input readonly="readonly" oninput="hitung()" name="t2_potensi" id="t2_potensi" type="text" placeholder="menit . . ." />
<!-- #aliran = (#v_potensi / (#a_potensi + #b_potensi + #t1_potensi + #t2_potensi)) - 0.1 -->
<input readonly="readonly" name="aliran" id="aliran" type="text" placeholder="liter/menit . . ." />
I use javascript to do the calculation process, to get a result for #t1_potensi and #t2_potensi. My problem start when i try to calculate overall (#aliran), my javascript function in particular to obtain the overall result can not work properly. Here my javascript for #t1_potensi, #t2_potensi, and #aliran.
//To get #t1_potensi
function hitungT1() {
var kecKm = document.getElementById('kecepatan_air').value;
var d1 = document.getElementById('jarak1').value;
var result = document.getElementById('t1_potensi');
//convert Km/jam to mph
var kecMph = Math.round(kecKm * 0.621371192);
//convert liter to miles
var d1Miles = d1 * 0.621371192;
var x = 60 / kecMph;
var kali = x.toFixed(1) * d1Miles.toFixed(2);
var hasil = 0.65 + kali;
result.value = hasil.toFixed(2);
}
//To get #t2_potensi
function hitungT2() {
var kecKm = document.getElementById('kecepatan_back').value;
var d2 = document.getElementById('jarak2').value;
var result = document.getElementById('t2_potensi');
//convert Km/jam to mph
var kecMph = Math.round(kecKm * 0.621371192);
//convert liter to miles
var d1Miles = d2 * 0.621371192;
var x = 60 / kecMph;
var kali = x.toFixed(1) * d1Miles.toFixed(2);
var hasil = 0.65 + kali;
result.value = hasil.toFixed(2);
}
//To get #aliran
function hitung() {
var vol = document.getElementById('v_potensi').value;
var a = document.getElementById('a_potensi').value;
var b = document.getElementById('b_potensi').value;
var t1 = document.getElementById('t1_potensi').value;
var t2 = document.getElementById('t2_potensi').value;
var hasil = document.getElementById('aliran');
//convert liter to galon
var galon = Math.round(vol * 0.264172051);
var sumT = t1 + t2;
var sum = a + sumT + b;
var dev = galon / sum;
var result = Math.round(dev - 0.1);
hasil.value = result;
}
Does anyone can help me to solve my problem? or maybe make my javascript function more efficient. thanks.
Use parseFloat() on the numbers you're getting with document.getElementById('...').value:
//To get #t1_potensi
function hitungT1() {
var kecKm = parseFloat(document.getElementById('kecepatan_air').value);
var d1 = parseFloat(document.getElementById('jarak1').value);
var result = document.getElementById('t1_potensi');
//convert Km/jam to mph
var kecMph = Math.round(kecKm * 0.621371192);
//convert liter to miles
var d1Miles = d1 * 0.621371192;
var x = 60 / kecMph;
var kali = x.toFixed(1) * d1Miles.toFixed(2);
var hasil = 0.65 + kali;
result.value = hasil.toFixed(2);
}
//To get #t2_potensi
function hitungT2() {
var kecKm = parseFloat(document.getElementById('kecepatan_back').value);
var d2 = parseFloat(document.getElementById('jarak2').value);
var result = document.getElementById('t2_potensi');
//convert Km/jam to mph
var kecMph = Math.round(kecKm * 0.621371192);
//convert liter to miles
var d1Miles = d2 * 0.621371192;
var x = 60 / kecMph;
var kali = x.toFixed(1) * d1Miles.toFixed(2);
var hasil = 0.65 + kali;
result.value = hasil.toFixed(2);
}
//To get #aliran
function hitung() {
var vol = parseFloat(document.getElementById('v_potensi').value);
var a = parseFloat(document.getElementById('a_potensi').value);
var b = parseFloat(document.getElementById('b_potensi').value);
var t1 = parseFloat(document.getElementById('t1_potensi').value);
var t2 = parseFloat(document.getElementById('t2_potensi').value);
var hasil = document.getElementById('aliran');
//convert liter to galon
var galon = Math.round(vol * 0.264172051);
var sumT = t1 + t2;
var sum = a + sumT + b;
var dev = galon / sum;
var result = Math.round(dev - 0.1);
hasil.value = result;
}
Also, it's a bit tricky to me why you call the hitung() function only after editing one of the first three text boxes. Why not call all three functions every time any field is changed? Wouldn't that be better?
Up to you. Also, after you've placed parseFloat calls like above, please use console.log(string or variable to log), e.g. console.log('dev is: ' + dev). That way you can easily debug your code - see what all the values are during any calculation.
Also, do you really need to round the final result?
I'm having trouble getting this bit of javascript to work. Whenever I try it inputs nothing into my div. It just adds ?weight=NumberInputed&measure=lbsOrkgs&submit=Submit to the URL.
<h2>How small must you be to become a black hole?</h2>
<form name="form1">
<input id="howMuch" type="number" name="weight" placeholder="How much do you weigh?">
<input type="radio" name="measure" value="lbs" checked="true">lbs
<input type="radio" name="measure" value="kgs">kgs
<input type="submit" name="submit" value="Submit" onClick="calc(); return false;">
</form>
<br/>
<div id="insert"><div/>
<script language="JavaScript" type="Text/JavaScript">
function calc() {
var speedOfLight = 299792458.0;
var gravityConstantYoctometre = 66738400000000.0;
var finalHeight = 0.0;
var weight = document.form1.weight.value;
var measure = document.form1.measure.value;
measure = measure.trim();
if (measure !== "kgs"){
weight *= 0.4536;
}
finalHeight = (4.0 * gravityConstantYoctometre * weight)/Math.pow(speedOfLight,2);
finalHeight = (finalHeight).toFixed(5);
var message = '<em>You would have to be ' + finalHeight + ' yoctometres (1 metre x 10<sup>-24</sup>) tall before you would become a black hole.</em>';
document.getElementById('insert').innerHTML = message;
}
</script>
Without the .trim() function, it executes perfectly, except for the fact that it will not recognize measure equaling anything resembling 'lbs' or 'kgs'. What is happening here?
Here: http://jsfiddle.net/dJJjr/1/
function calc() {
var speedOfLight = 299792458.0;
var gravityConstantYoctometre = 66738400000000.0;
var finalHeight = 0.0;
var weight = document.getElementById("howMuch").value;
var radio = document.getElementsByName('measure');
var measure = ""
for(var i =0; i< radio.length; i++)
{
if(radio[i].checked)
measure = radio[i].value;
}
measure = measure.trim();
alert(measure); //For testing purpose
alert(weight); //For testing purpose
if (measure !== "kgs"){
weight *= 0.4536;
}
finalHeight = (4.0 * gravityConstantYoctometre * weight)/Math.pow(speedOfLight,2);
finalHeight = (finalHeight).toFixed(5);
var message = '<em>You would have to be ' + finalHeight + ' yoctometres (1 metre x 10<sup>-24</sup>) tall before you would become a black hole.</em>';
document.getElementById('insert').innerHTML = message;
}