Sum being zero when calculated using javascript - javascript

var num1=document.getElementById("number1");
var num2=document.getElementById("number2");
var k=Number(num1.value);
var l=Number(num2.value);
function add(){
onCout(k,l,function result(a,b){
return a+b;
});
}
function onCout(c,d,callback){
var result=callback(c,d);
output.innerHTML=result;
}
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
Num1: <input type="text" id="number1" />
Num2: <input type="text" id="number2" />
<div id="output"></div>
<button id="add" onclick="add()">Add</button>
</body>
</script>
</html>
i want to calculate the sum of two input text field when user clicks the add button.But when I did
console.log(k); I am getting zero.I dont know hoe it became zero.I also searched how to take the value from text field and they way to take is using document.getElementById("id").value.I have done the same but my result is not coming.

Get the value of k & l inside the add function. That is because before clicking the button those values are empty
var num1 = document.getElementById("number1");
var num2 = document.getElementById("number2");
function add() {
var k = Number(num1.value);
var l = Number(num2.value);
onCout(k, l, function result(a, b) {
return a + b;
});
}
function onCout(c, d, callback) {
var result = callback(c, d);
output.innerHTML = result;
}
Num1: <input type="text" id="number1" /> Num2: <input type="text" id="number2" />
<div id="output"></div>
<button id="add" onclick="add()">Add</button>
You are getting 0 because initially the fields are empty and Number('') will give 0
var num1 = document.getElementById("number1");
var num2 = document.getElementById("number2");
var k = Number(num1.value);
var l = Number(num2.value);
console.log(num1.value, num2.value) // value is empty string
console.log(k, l); // NUmber('') is 0
function add() {
onCout(k, l, function result(a, b) {
return a + b;
});
}
function onCout(c, d, callback) {
var result = callback(c, d);
output.innerHTML = result;
}
Num1: <input type="text" id="number1" /> Num2: <input type="text" id="number2" />
<div id="output"></div>
<button id="add" onclick="add()">Add</button>

You are getting 0 because youre getting the values of k and l on page load and not inside your add function which gets called on button click.

You should get the updated values inside the function instead of getting the initials one on load, this can be done as follows:
function add(){
var k=Number(num1.value);
var l=Number(num2.value);
onCout(k,l,function result(a,b){
return a+b;
});
}

var k=Number(num1.value);
var l=Number(num2.value);
the value must be fetched inside the function add(), as the values will be dynamic.
In the code shown in question, values are fetched only once which makes them pointing to initial only and not change dynamically with user input
var num1=document.getElementById("number1");
var num2=document.getElementById("number2");
function add(){
var k=Number(num1.value);
var l=Number(num2.value);
onCout(k,l,function result(a,b){
return a+b;
});
}
function onCout(c,d,callback){
var result=callback(c,d);
output.innerHTML=result;
}
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
Num1: <input type="text" id="number1" />
Num2: <input type="text" id="number2" />
<div id="output"></div>
<button id="add" onclick="add()">Add</button>
</body>
</script>
</html>

Related

Passing user input from html to javascript as array (to get tensor1d)

So I've been trying to get user input to calculate outer product of two vectors using tensorflow.js but I couldn't figure out how to get an array from html to pass it into javascript. for example inside the calculator function const a has to be something like this tf.tensor1d([1, 2, 3])
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script src="https://cdn.jsdelivr.net/npm/#tensorflow/tfjs#2.0.0/dist/tf.min.js"></script>
</head>
<body>
<h1 class="text1">Welcome to vector cross product calculator!</h1>
<h2>Please enter two vectors like 1,2,3 and 3,2,1</h2>
<label>vector a</label>
<input type="text" name="vectora" id="vectora" class="vectora" placeholder="enter a vector like 1,2,3"> <br>
+<br>
<label>vector b</label>
<input type="text" name="vectorb" id="vectorb" class="vectorb" placeholder="enter a vector like 1,2,3"><br>
<button type="button" class="btn btn-info" onclick="calculator()">submit</button><br><br>
<div class="screen" id="screen1"></div>
</button>
<script>
function calculator(){
var vectora = document.getElementById("vectora").value;
var vectorb = document.getElementById("vectorb").value;
const a = tf.tensor1d(vectora);
const b = tf.tensor1d(vectorb);
var c = tf.outerProduct(a, b);
document.getElementById("screen1").innerHTML=c;
}
</script>
</body>
</html>
A utility function getArray can help.
function getArray(data) {
return data.split(',').map(s => +s)
}
function calculator(){
var vectora = document.getElementById("vectora").value;
var vectorb = document.getElementById("vectorb").value;
const a = tf.tensor1d(getArray(vectora));
const b = tf.tensor1d(getArray(vectorb));
var c = tf.outerProduct(a, b);
document.getElementById("screen1").innerHTML=c;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script src="https://cdn.jsdelivr.net/npm/#tensorflow/tfjs#2.0.0/dist/tf.min.js"></script>
</head>
<body>
<h1 class="text1">Welcome to vector cross product calculator!</h1>
<h2>Please enter two vectors like 1,2,3 and 3,2,1</h2>
<label>vector a</label>
<input type="text" name="vectora" id="vectora" class="vectora" placeholder="enter a vector like 1,2,3"> <br>
+<br>
<label>vector b</label>
<input type="text" name="vectorb" id="vectorb" class="vectorb" placeholder="enter a vector like 1,2,3"><br>
<button type="button" class="btn btn-info" onclick="calculator()">submit</button><br><br>
<div class="screen" id="screen1"></div>
</button>
<script>
function getArray(data) {
return data.split(',').map(s => +s)
}
function calculator(){
var vectora = document.getElementById("vectora").value;
var vectorb = document.getElementById("vectorb").value;
const a = tf.tensor1d(getArray(vectora));
const b = tf.tensor1d(getArray(vectorb));
var c = tf.outerProduct(a, b);
document.getElementById("screen1").innerHTML=c;
}
</script>
</body>
</html>

Empty input fields/values after form submit

I've got a very simple form and I'm want the values to empty when I submit in order to use again without refreshing the page. What I've got isn't working for some reason.
My initial idea was to set the values of the inputs to empty strings on form submit, but when I log them into the console they don't do that. Anyone know what I'm doing wrong here?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<form id="form">
<input id="volume" type="text" />
<input id="denied" type="text" />
<input id="charges" type="number" step="any" />
<button id="submit" type="btn-submit">Submit</button>
</form>
<div class="results">
<p class="rate">Current Denial Rate: </p>
<p class="recoverable">Recoverable Dollars: </p>
</div>
<script src="script.js"></script>
</body>
</html>
let form = document.getElementById("form");
let volume = document.getElementById("volume");
let denied = document.getElementById("denied");
let charges = document.getElementById("charges");
let submit = document.getElementById("btn-submit");
let results = document.querySelector(".results");
let rate = document.querySelector(".rate");
let recoverable = document.querySelector(".recoverable");
form.onsubmit = function (e) {
e.preventDefault();
volume = volume.value;
denied = denied.value;
charges = charges.value;
let curDenialRate = parseFloat((denied / volume) * 100);
charges = parseFloat(charges * 0.4);
function formatNumber(num) {
let formattedNum = num.toFixed(2);
return formattedNum;
}
let recoverableDollars = "$" + formatNumber(charges);
curDenialRate = formatNumber(curDenialRate) + "%";
rate.append(curDenialRate);
recoverable.append(recoverableDollars);
volume = " ";
denied = " ";
charges = " ";
return false;
};
Use HTMLFormElement.reset():
let form = document.getElementById("form");
const volume = document.getElementById("volume");
const denied = document.getElementById("denied");
const charges = document.getElementById("charges");
let submit = document.getElementById("btn-submit");
let results = document.querySelector(".results");
let rate = document.querySelector(".rate");
let recoverable = document.querySelector(".recoverable");
form.onsubmit = function(e) {
e.preventDefault();
let a = volume.value;
let b = denied.value;
let c = charges.value;
let curDenialRate = parseFloat((b / a) * 100);
c = parseFloat(c * 0.4);
function formatNumber(num) {
let formattedNum = num.toFixed(2);
return formattedNum;
}
let recoverableDollars = "$" + formatNumber(c);
curDenialRate = formatNumber(curDenialRate) + "%";
rate.append(curDenialRate);
recoverable.append(recoverableDollars);
form.reset();
return false;
};
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<form id="form">
<input id="volume" type="text" />
<input id="denied" type="text" />
<input id="charges" type="number" step="any" />
<button id="submit" type="btn-submit">Submit</button>
</form>
<div class="results">
<p class="rate">Current Denial Rate: </p>
<p class="recoverable">Recoverable Dollars: </p>
</div>
<script src="script.js"></script>
</body>
</html>
How you are clearing values will not work. You are trying to change the variable but that will not affect the DOM element or its value.
You will have to use the below code with value property to change the value.
document.getElementById("volume").value= " ";
document.getElementById("denied").value= " ";
document.getElementById("charges").value= " ";

Calculating VAT

I'm creating a simple web app that takes two values, outputs a total, then displays VAT of 20% in the VAT field (to clarify, this shows 20% of the total previously calculated) then it should have a final grand total field which adds the total to the VAT, however I haven't gotten round to this part as I'm having difficulty calculating the VAT in my code, this is what I have thus far:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form>
Value 1: <input type="text" name="val1"><br>
Value 2: <input type="text" name="val2"><br>
Total: <input type="text" name="sum"><br>
VAT:<input type="text" name="vat"><br>
<input type="button" value="Sum" onclick="sumTotal() + vatCalc()">
</form>
<script>
function sumTotal() {
let val1 = document.getElementsByName("val1")[0].value;
let val2 = document.getElementsByName("val2")[0].value;
let sum = Number(val1) + Number(val2);
document.getElementsByName("sum")[0].value = sum;
}
function vatCalc () {
// let vat= document.getElementsByName("vat")
var sumVat = 20;
let vat = (sum/100)*(sumVat+100);
document.getElementsByName("vat")[0].value = vat;
}
</script>
</body>
</html>
any help would be greatly appreciated please, thanks!
I've edited your functions so now sumtotal calls your vat function.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form>
Value 1: <input type="text" name="val1"><br>
Value 2: <input type="text" name="val2"><br>
Total: <input type="text" name="sum"><br>
VAT:<input type="text" name="vat"><br>
<input type="button" value="Sum" onclick="sumTotal()">
</form>
<script>
function sumTotal() {
let val1 = document.getElementsByName("val1")[0].value;
let val2 = document.getElementsByName("val2")[0].value;
let sum = Number(val1) + Number(val2);
document.getElementsByName("sum")[0].value = sum;
vatCalc(sum);
}
function vatCalc (sum) {
// let vat= document.getElementsByName("vat")
var sumVat =0.20;
let vat = sumVat*sum;
document.getElementsByName("vat")[0].value = vat;
}
</script>
</body>
</html>

How Can I use form items in javascript

I want to use HTML form elements in JavaScript. I used them like this but it doesn't work:
<form name="M">
<input name="in1" type="text" id="in1">
<input type="button" name="btn1" id="btn1" value="Check" onclick="f1()">
</form>
<script src="script.js"></script>
...and the JavaScript code was like this:
var s1 = 60;
function f1() {
``
if (document.M.elements[0] == s1) {
window.location = 'tick.htm';
} else {
window.location = 'cross.htm';
}
}
What is wrong here?
Just to give some clarification on why this was not working. In the test, document.M.elements[0] is a reference to the input object, not the value of the input. Using document.M.elements[0].value gives us the current value of the input.
//Ignore this, for display only.
function output(msg) {
var element = document.getElementById('output');
element.innerHTML = msg;
};
function f1() {
var s1 = 60;
if (document.M.elements[0].value == s1) {
output('Pass');
} else {
output('Fail');
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<form name="M">
<input name="in1" type="text" id="in1">
<input type="button" name="btn1" id="btn1" value="Check" onclick="f1()">
</form>
<b id="output"></b>
</body>
</html>

how to display different function in a same textbox?

I have this html code with javascript. My average value displays correctly but my find minimum is not displaying anything. Its supposed to show when the user clicks on the find min button on the box.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Calculate Your Grade</title>
<link rel="stylesheet" href="calc.css">
<script>
var $ = function (id) {
return document.getElementById(id);
}
var calculateGrade = function () {
var exam1 = parseFloat($("exam1").value);
var exam2 = parseFloat($("exam2").value);
var exam3=parseFloat($("exam3").value);
if (isNaN(exam1) || isNaN(exam2) ) {
alert("All three entries must be numeric");
}
else {
var average = (exam1 + exam2 + exam3) / 3;
$("average").value = average;
}
}
var min = function () {
var exam1 = parseFloat($("exam1").value);
var exam2 = parseFloat($("exam2").value);
var exam3=parseFloat($("exam3").value);
if ( (exam1<exam2) && (exam1<exam3)){
$("mini").value=exam1;}
else if ((exam2<exam1) && (exam2<exam3)){
$("mini").value=exam2;}
else {
$("mini").value=exam3;
}
}
window.onload = function () {
$("calculate").onclick = calculateGrade;
$("mini").onclick = min;
$("exam1").focus();
}
</script>
</head>
<body>
<section>
<h1>Calculate Average</h1>
<label for="exam1">Exam1:</label>
<input type="text" id="exam1"><br>
<label for="exam2">Exam2:</label>
<input type="text" id="exam2"><br>
<label for="exam3">Exam3:</label>
<input type="text" id="exam3"><br>
<label for="average"></label>
<input type="text" id="average"disabled ><br>
<label> </label>
<input type="button" id="calculate" value="Calc Avg">
<input type="button" id="mini" value="Find min">
</section>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Calculate Your Grade</title>
<link rel="stylesheet" href="calc.css">
<script>
var $ = function (id) {
return document.getElementById(id);
}
var average = function () {
var exam1 = parseFloat($("exam1").value);
var exam2 = parseFloat($("exam2").value);
var exam3 = parseFloat($("exam3").value);
if (isNaN(exam1) || isNaN(exam2) || isNaN(exam3)) {
alert("All three entries must be numeric");
}
else {
var average = (exam1 + exam2 + exam3) / 3;
$("result").value = average;
}
}
var min = function () {
var exam1 = parseFloat($("exam1").value);
var exam2 = parseFloat($("exam2").value);
var exam3 = parseFloat($("exam3").value);
if (isNaN(exam1) || isNaN(exam2) || isNaN(exam3)) {
alert("All three entries must be numeric");
} else {
$("result").value = Math.min(exam1,exam2,exam3);
}
}
window.onload = function () {
$("average").onclick = average;
$("mini").onclick = min;
$("exam1").focus();
}
</script>
</head>
<body>
<section>
<h1>Calculate</h1>
<label for="exam1">Exam1:</label>
<input type="text" id="exam1"><br>
<label for="exam2">Exam2:</label>
<input type="text" id="exam2"><br>
<label for="exam3">Exam3:</label>
<input type="text" id="exam3"><br>
<label for="average"></label>
<input type="text" id="result" disabled ><br>
<label> </label>
<input type="button" id="average" value="Calc Avg">
<input type="button" id="mini" value="Find min">
</section>
</body>
</html>
The issue is with the min function. Instead of setting the value of textbox (probably, missing in your code example) you are setting the value of button "mini" (which is incorrect).
Update:
You need to be including one more textbox <input type="text" id="txtMin" disabled ><br>
and update your min function to set the value of it, as follows:
$("txtMin").value=exam1;
...
$("txtMin").value=exam2;
...
$("txtMin").value=exam3;

Categories