Can anyone help me to show the result of this calculation? JavaScript - javascript

Hi could anyone run this code correctly?
I learnt to make somthing similar to this
https://www.youtube.com/watch?v=vkBiEuZSq9s
but this is not a loan, it is a simple calculation
SMAL should be * 0.5
GAS * 6
CV as it is
result should be SMAL + GAS + CV
I am new to JavaScript and I need your help
Thanx
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" >
<script>
function calculate(){
var GAS = document.getElementById('GAS').value;
var SMAL = document.getElementById('SMAL').value;
var CV = document.getElementById('CV').value;
var GASAcal = (GAS * 6);
var SMALcal = (SMAL * 0.5);
var CVcal = (CV);
var total_score = CVcal + GAScal + SMALcal;
if(total_score ismap)
{
document.getElementById('total_score').innerHTML = "Total score = "+total_score;
}
}
</script>
</head>
<body dir="rtl">
<p> GAS <br><input id="GAS" type="number" min="0" max="5" step="" onchange="calculate" ></p>
<p> SMAL <br><input id="SMAL" type="number" min="0" max="100" value="1" onchange="calculate"></p>
<p> CV <br><input id="CV" type="number" min="1" max="20" value="1" onchange="calculate"></p>
<h2 id="total_score"></h2>
</body>
</html>

A couple things.
You have errors in your JavaScript. Like another person said, get familiar with your browser development tools, and using console.log() and/or alert().
You've stumbled upon an age-old issue with oninput event for Input elements. It's buggy, and depends on browser and browser version.
Anyway, without getting into too much detail (which I'm sure you can search the web for answers to), I've included a working version of your html page here. My JavaScript logic here is a poor man's version so that you can see what I did to capture the oninput events.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script>
var calculate;
document.addEventListener("DOMContentLoaded", function(event) {
// GAS
document.getElementById('GAS').oninput = function() {
this.onkeydown = null;
calculate.call(this);
};
document.getElementById('GAS').onkeydown = function() {
calculate.call(this);
};
// SMAL
document.getElementById('SMAL').oninput = function() {
this.onkeydown = null;
calculate.call(this);
};
document.getElementById('SMAL').onkeydown = function() {
calculate.call(this);
};
// CV
document.getElementById('CV').oninput = function() {
this.onkeydown = null;
calculate.call(this);
};
document.getElementById('CV').onkeydown = function() {
calculate.call(this);
};
calculate = function (){
//console.log("calcing...");
var GAS = document.getElementById('GAS').value;
var SMAL = document.getElementById('SMAL').value;
var CV = document.getElementById('CV').value;
var GAScal = (GAS * 6);
var SMALcal = (SMAL * 0.5);
var CVcal = (CV);
var total_score = CVcal + GAScal + SMALcal;
if(total_score)
{
//total_score = 10.620000000000001
//total_score = 10.625000000000001
document.getElementById('total_score').innerHTML = "Total score = "+ roundNumber(total_score, 2);
}
//console.log(total_score);
//console.log("calcing done");
}
// this rounds your number, and scale is to what precision we round to and return
function roundNumber(num, scale) {
if(!("" + num).includes("e")) {
return +(Math.round(num + "e+" + scale) + "e-" + scale);
} else {
var arr = ("" + num).split("e");
var sig = ""
if(+arr[1] + scale > 0) {
sig = "+";
}
return +(Math.round(+arr[0] + "e" + sig + (+arr[1] + scale)) + "e-" + scale);
}
}
})
</script>
</head>
<body dir="rtl">
<p>GAS
<br>
<input id="GAS" type="number" min="0" max="5" step="" oninput="calculate">
</p>
<p>SMAL
<br>
<input id="SMAL" type="number" min="0" max="100" value="1" oninput="calculate">
</p>
<p>CV
<br>
<input id="CV" type="number" min="1" max="20" value="1" oninput="calculate">
</p>
<h2 id="total_score"></h2>
</body>
</html>

Related

How can I grab an HTML slider value as an integer for JavaScript?

I'm trying to obtain a value out of an HTML slider so I can dynamically use it as an integer in JavaScript.The problem I'm having is I can't seem to use the value as a proper integer.
For example, if my slider value was 5 & if l tried to store it in a variable and add 10, it would output as '510' instead.
Maybe I'm an idiot and missing something very fundamental or simple, but it always ends up as a string in the end.I have tried parseInt() as well, but it doesn't seem to help.
I've set up a simple example of code below:
JS
var sliderUnit = document.getElementById("slider");
var outputUnit = document.getElementById("amtOutput");
var a = 0;
var b = 10;
outputUnit.innerHTML = sliderUnit.value;
sliderUnit.oninput = function(){
outputUnit.innerHTML = this.value;
console.log(sliderUnit.value);
a = this.value;
parseInt(a);
}
function test(){
b += a;
console.log("b: " + b + " | a: " + a);
}
HTML
<div class="sliderContainer">
<input type="range" min="1" max="15" value="7" id="slider">
<input type="submit" value="Submit" onclick="test()" />
| Slider number: <span id="amtOutput"></span>
</div>
The problem is that your are calling the parseInt(a) but the returned Integer value is not being handled properly, you should do as this a = parseInt(a);
var sliderUnit = document.getElementById("slider");
var outputUnit = document.getElementById("amtOutput");
var a = 0;
var b = 10;
outputUnit.innerHTML = sliderUnit.value;
sliderUnit.oninput = function(){
outputUnit.innerHTML = this.value;
console.log(sliderUnit.value);
a = this.value;
a = parseInt(a); // Change this line
}
function test(){
b += a;
console.log("b: " + b + " | a: " + a);
}
<div class="sliderContainer">
<input type="range" min="1" max="15" value="7" id="slider">
<input type="submit" value="Submit" onclick="test()" />
| Slider number: <span id="amtOutput"></span>
</div>
If not the variable a will continue to be a string becouse it wasn't changed
You need to parse the string as int using parseInt.
Working code:
var sliderUnit = document.getElementById("slider");
var outputUnit = document.getElementById("amtOutput");
var a = 0;
var b = 10;
outputUnit.innerHTML = sliderUnit.value;
sliderUnit.oninput = function(){
outputUnit.innerHTML = this.value;
console.log(sliderUnit.value);
a = this.value;
parseInt(a);
}
function test(){
b = parseInt(b)
a = parseInt(a);
b += a;
console.log("b: " + b + " | a: " + a);
}
<div class="sliderContainer">
<input type="range" min="1" max="15" value="7" id="slider">
<input type="submit" value="Submit" onclick="test()" />
| Slider number: <span id="amtOutput"></span>
</div>
Working JSFiddle

I cannot figure out why my html page is not running my external javascript file

I have two javascript functions called CalculateFV() which is used to calculate my future value by grabbing the inputs from the processEntries() function and then display the result in the future_value text box on the HTML page but I currently cannot see why it is not functioning correctly and the button is not working to calculate my result
I am also using atom as my editor
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Future Value Calculator</title>
<link rel="stylesheet" href="future_value.css">
<script src="future_value.js"></script>
</head>
<body>
<main>
<h1>Future Value Calculator</h1>
<label for="investment">Total Investment:</label>
<input type="text" id="investment"><br>
<label for="rate">Annual Interest Rate:</label>
<input type="text" id="rate">%<br>
<label for="years">Number of Years:</label>
<input type="text" id="years"><br>
<label for="future_value">Future Value:</label>
<input type="text" id="future_value" disabled><br>
<label> </label>
<input type="button" id="calculate" value="Calculate"><br>
</main>
</body>
</html>
var $ = function(id) {
return document.getElementById(id);
};
var calculateFV = function(investment_amount, interest_rate, number_of_years){
var futureValue;
futureValue = investment_amount
for(var i = 1; i <= number_of_years; i++){
futureValue = futureValue + (futureValue * interest_rate / 100);
}
return futureValue;
}
var processEntries = function(){
var investment_amount = $("investment").value;
var interest_rate = $("rate").value;
var number_of_years = $("years").value;
$("future_value").value = calculateFV(investment_amount, interest_rate, number_of_years);
}
window.onLoad = function(){
$("calculate").value = processEntries;
$("investment").focus();
}
The onLoad function wasn't being handled correctly and you need to register a click listener on the calculate button. Try this:
future_value.js:
"use strict";
var $ = function(id) {
return document.getElementById(id);
};
var calculateFV = function(investment_amount, interest_rate, number_of_years){
var futureValue;
futureValue = investment_amount
for(var i = 1; i <= number_of_years; i++){
futureValue = futureValue + (futureValue * interest_rate / 100);
}
return futureValue;
}
var processEntries = function(){
var investment_amount = $("investment").value;
var interest_rate = $("rate").value;
var number_of_years = $("years").value;
$("future_value").value = calculateFV(investment_amount, interest_rate, number_of_years);
}
window.addEventListener('load', (event) => {
$('calculate').addEventListener('click', processEntries);
$("investment").focus();
});
Using this I see the future value input populated after I click calculate. Note the changes I made towards the bottom.

How to fix the show/hide button on input change based on if/else condition

I am learning jquery. I have an HTML & jquery code. I want to show the button only if my answer is true on input value otherwise it should stay hidden. Also, I want to show the questions on my screen. See, if anyone can help. thanks
var random = Math.random();
var range = random * 2;
var incrment = range + 1;
var floor = Math.floor(incrment);
var ques1 = "what comes after 4?";
var ans = 5;
$(document).ready(function() {
$("#bot").keyup(function() {
if (ans == floor) {
$("#pete").css("display", "block");
} else {
$("#pete").css("display", "none");
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Name: <input type="text" id="bot" required="required"></p>
<input type="submit" id="pete" style="display:none;">
use show() and hide() functions and i dont know when your floor and ans will be equal.
var random = Math.random();
var range = random * 2 ;
var incrment = range + 1;
var floor = Math.floor(incrment);
var ans = 5;
floor=6; //for testing i gave
$("#bot").keyup(function() {
if (ans == $('#bot').val())
$("#pete").show();
else
$("#pete").hide();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>What number comes after 4?</label>
<input type="number" id="bot" required="required"/>
<input type="submit" id="pete" style="display:none;" >
Here is the complete code for your requirement .
Use innerHTML to priint the question in the screen and .value to obtain the value entered by user ..
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge;chrome=1" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<p id="question"></p>
<p>Name: <input type="text" id="bot" required="required"></p>
<input type="submit" id="pete" style="display:none;" >
</body>
</html>
<script type="text/javascript">
var random = Math.random();
var range = random * 2 ;
var incrment = range + 1;
var floor = Math.floor(incrment);
var ques1 = "what comes after 4?";
document.getElementById('question').innerHTML = ques1;
var ans = 5;
$("#bot").keyup(function() {
var ansFromInput = document.getElementById('bot').value;
console.log("ans , floor" , ans , ansFromInput);
if (ans == ansFromInput) {
$("#pete").css("display", "block");
}
else {
$("#pete").css("display", "none");
}
});
</script>
You can do something like that ,
Here using class to hide the button, we can add and remove class to achieve that.
var random = Math.random();
var range = random * 2;
var incrment = range + 1;
var floor = Math.floor(incrment);
var ques1 = "what comes after 4?";
var floor = 5;
$('#ques').text(ques1);
$(document).ready(function() {
$('#bot').on('input',function(e){
if ($('#bot').val() == floor) {
$("#pete").removeClass('hide');
} else {
$("#pete").addClass('hide');
}
});
});
.hide{
display:none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label> <p id="ques"> </p> </label>
<p><input type="text" id="bot" required="required"></p>
<input type="submit" id="pete" class="hide">

Use Javascript to Make Calculator

Good Day - I am Learning Javascript, I am trying to create a Calculator to calculate ampere-turn to magnetize a tool (it's related to my job.) I am trying to use some formulas to calculate this ampere-turn. The code seems fine to me, but it's not working. I put some values in the form, and click button submit, but no result found and i don't know why this happens.
I am sharing my code here for your kind review. and help me to fix this problem.
thank you.
function ampereturn()
{
var inputOD = Number(document.ampereturn.inputod.value);
var inputLen = Number(document.ampereturn.inputlen.value);
var InputID = Number(document.ampereturn.Inputid.value);
var InputTurn = Number(document.ampereturn.Inputturn.value);
var ans;
var ldratio = inputLen/inputOD;
var coilradius = InputID/2;
var toolradius = inputOD/2;
var pi = 3.14;
var xcoil = (coilradius * coilradius) * pi;
var xtool = (toolradius * toolradius) * pi;
var factor = xtool/xcoil;
var text = "Use Intermediate Fill-factor formula:";
if(factor >= 0.5)
{
ans = 35000/(ldratio+2)*Inputturn;
document.getElementById('sum').innerHTML = ans;
}
if(factor <= 0.1)
{
ans = 45000/ldratio*Inputturn;
document.getElementById('sum').innerHTML = ans;
}
else
{
document.getElementById('sum').innerHTML = text;
}
}
<form name="ampereturn">
<div class="w3-half w3-margin-top">
<label>Tool OD:</label>
<input id="inputod" class="w3-input w3-border" type="number" placeholder="Input Tool Outer Dia:">
</div>
<div class="w3-half w3-margin-top">
<label>Tool Lenght:</label>
<input id="inputlen" class="w3-input w3-border" type="number" placeholder="Input Tool Length">
</div>
<div class="w3-half w3-margin-top">
<label>Coil ID:</label>
<input id="Inputid" class="w3-input w3-border" type="number" placeholder="Input Coil Internal Dia:">
</div>
<div class="w3-half w3-margin-top">
<label>Coil Turn:</label>
<input id="Inputturn" class="w3-input w3-border" type="number" placeholder="Input Number of turn in coil:">
</div>
<div class="w3-half w3-margin-top">
<label>Required Ampere:</label>
<p id="sum"></p>
</div>
<button type="button" onclick="ampereturn()">Submit</button>
</form>
<br><hr>
thank you in advance. ....
Change the function name which is same as the form name.
Change Inputturn to InputTurn in the if condition.
Required Code:
function Ampereturn()
{
var inputOD = Number(document.ampereturn.inputod.value);
var inputLen = Number(document.ampereturn.inputlen.value);
var InputID = Number(document.ampereturn.Inputid.value);
var InputTurn = Number(document.ampereturn.Inputturn.value);
var ans;
var ldratio = inputLen/inputOD;
var coilradius = InputID/2;
var toolradius = inputOD/2;
var pi = 3.14;
var xcoil = (coilradius * coilradius) * pi;
var xtool = (toolradius * toolradius) * pi;
var factor = xtool/xcoil;
var text = "Use Intermediate Fill-factor formula:";
if(factor >= 0.5)
{
ans = 35000/(ldratio+2)*InputTurn;
document.getElementById('sum').innerHTML = ans;
}
else if(factor <=0.1)
{
ans = 45000/ldratio*InputTurn;
document.getElementById('sum').innerHTML = ans;
}
else
{
document.getElementById('sum').innerHTML = text;
}
}

Filter table rows based on JavaScript calculation output

I need to filter rows in the following table based on the output of a JavaScript calculation.
I need the output of:
var loantovalue = x / h * 100;
to filter rows if the value of loantovalue is more than the value of <td class="ltv">.
I am not really sure how to go about doing this? Any help would be appreciated please.
I filter the data elsewhere using checkboxes, and use this:
$(document).ready(function() {
$("#type :checkbox").click(function() {
$("td").parent().hide();
$("#type :checkbox:checked").each(function() {
$("." + $(this).val()).parent().show();
});`
So I guess I need to do something similar to the output of loantovalue?
$(document).ready(function() {
$("#type :checkbox").click(function() {
$("td").parent().hide();
$("#type :checkbox:checked").each(function() {
$("." + $(this).val()).parent().show();
});
});
$("#fee :checkbox").click(function() {
$("td").parent().hide();
$("#fee :checkbox:checked").each(function() {
$("." + $(this).val()).parent().show();
});
});
});
var repayment = function() {
};
window.onload = function() {
document.repaymentcalc.homevalue.onchange = repayment;
document.repaymentcalc.loanamount.onchange = repayment;
document.repaymentcalc.numberpayments.onchange = function() {
$('#years').html(this.value + ' years');
};
makeSomething();
};
function makeSomething() {
$('tbody tr').each(function(idx, row) {
var $row = $(row);
var initialRateCell = $row.find('td')[2];
var repaymentCell = $row.find('td')[7];
var rate = parseFloat($(initialRateCell).html());
var repaymentVal = computeRepayment(rate);
$(repaymentCell).html(repaymentVal.repayment);
});
}
$("#myForm :input").change(function() {
makeSomething();
});
function computeRepayment(rate) {
var x = parseInt(document.repaymentcalc.loanamount.value, 10);
var y = parseInt(rate * 100, 10) / 120000;
var z = parseInt(document.repaymentcalc.numberpayments.value, 10) * 12;
var h = parseInt(document.repaymentcalc.homevalue.value, 10);
var repayment = y * x * Math.pow((1 + y), z) / (Math.pow((1 + y), z) - 1);
var loantovalue = x / h * 100;
$('#ltv').text('Loan to Value: ' + loantovalue.toFixed(2) + '%');
var year = z / 12;
return {
repayment: '£' + repayment.toFixed(2),
loantovalue: loantovalue,
year: year
}
}
<html>
<head>
<link href='https://fonts.googleapis.com/css?family=Droid+Sans' rel='stylesheet' type='text/css'>
</head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form name="repaymentcalc" id="myForm" action="">
<h3>Mortgage Needs</h3>
<p>Home Value £<input type="number" id="homevalue" value="250000" style="width: 75px"></p>
<p>Loan Amount £<input type="number" id="loanamount" value="200000" style="width: 75px"></p>
<p id="ltv">Loan to Value: 80.0%</p>
<section id="type">
<p id="Mortgage Type">Mortgage Type</p>
<input type="checkbox" name="type" value="t2" id="t2" checked/>2yr Fixed<br>
<input type="checkbox" name="type" value="t3" id="t3" checked/>3yr Fixed<br>
<input type="checkbox" name="type" value="t5" id="t5" checked/>5yr Fixed<br>
</section>
<section id="fee">
<p id="Fee">Fee</p>
<input type="checkbox" name="fee" value="fee" id="fee" checked/>Fee<br>
<input type="checkbox" name="fee" value="nofee" id="nofee" checked/>No Fee<br>
</section>
Term <input type="range" id="numberpayments" value="25" min="1" max="40" style="width: 75px"> <p id="years" style="display:inline-block;"> 25 years</p>
</form>
<table id="mortgagetable">
<thead>
<tr class="producthd"><th class="lenderhd">Lender</th><th class="typehd">Mortgage Type</th><th class="initialratehd">Initial Rate (%)</th><th class="rateshd">Reversion Rate (%)</th><th class="rateshd">Overall APR (%)</th><th class="feehd">Product Fee (£)</th><th class="ltvhd">Maximum LTV (%)</th><th class="repaymenthd">Initial Repayment</th><th class="applylinkhd"></th></tr>
</thead>
<tbody>
<tr class="product"><td class="lender"></td><td class="t2">2yr Fixed</td><td class="initialrate">1.29</td><td class="rates">4.74</td><td class="rates">4.3</td><td class="fee">999</td><td class="ltv">60</td><td class="repayment"></td></td></tr>
<tr class="product"><td class="lender"></td><td class="t2">2yr Fixed</td><td class="initialrate">1.39</td><td class="rates">4.24</td><td class="rates">3.9</td><td class="fee">1495</td><td class="ltv">60</td><td class="repayment"></td><td class="applylink"></td></tr>
</tbody>
</table>
In document ready function add the following code:
FilterByMaxLTV();
function FilterByMaxLTV() {
$("#mortgagetable tbody tr").each(function () {
var l = parseFloat($('#loanamount').val());
var h = parseFloat($('#homevalue').val());
var loneToValue = parseFloat((l/h)*100).toFixed(2);
$('#ltv').text('Loan to Value: ' + loneToValue + '%');
//Get the number from the right td.
var x = parseFloat($(this).find(".ltv").text());
console.log(x);
if(x>loneToValue){
$(this).hide();
}
else{
$(this).show();
}
});
}
$('#homevalue,#loanamount').change(function(){
FilterByMaxLTV();
});
JSFiddle
What we are doing here is that we have created one function to filter the values. And we are calling the same function on page load (document ready), and on textbox value change.
Note: The calculation can be wrong. Similarly I may have put the wrong sign (less than/ greater than)
Also refer this jsFiddle - here the keyup function is used instead of change function to make it much more dynamic
Not sure I understand all of your code, but in general it could be done like this:
//For every tr in the table.
$("#mortagetable tr").each(function() {
//I assume that the variable loantovalue is defiend globally somewhere,
//since I can not understand how it is supposed to be calculated from your question.
//Get the number from the right td.
var x = parseInt($(this).find(".ltv").text())
//Toggel the visibility of this tr.
$(this).toggle(loantovalue > x);
});
Disclaimar: I have not tested this code.

Categories

Resources