I'm working on a tax calculator using HTML and Javascript. It needs to accept two user inputs ("Total owed" and "Your payment") and calculate what percentage "Your payment" is of "Total owed". Then they should be displayed within the "answerParagraph" tag. What is the best way to do this?
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div id="getPercentage">
<div id="total">
Total owed:
<input id="totalInput" type="text">
</div>
<div id="payment">
Your payment:
<input id="paymentInput" type="text">
</div>
<button onclick="handlers.getPercentage()">Get percentage</button>
</div>
<div>
<p id="answerParagraph">
</p>
</div>
<script>
var taxes = {
getPercentage: function(total, payment) {
var percentage = (Math.floor((payment / total) * 100));
},
}
var handlers = {
getPercentage: function() {
var totalInput = document.getElementById('totalInput');
var paymentInput = document.getElementById('paymentInput');
var answer = taxes.getPercentage(totalInput.value, paymentInput.value);
}
}
</script>
</body>
</html>
You have to return the answer from taxes.getPercentage function
getPercentage: function (total, payment) {
var percentage = (Math.floor((payment / total) * 100));
return percentage;
}
And display in your answerParagraph. So, in handlers.getPercentage :
...
var answer = taxes.getPercentage(totalInput.value, paymentInput.value);
answerParagraph.innerHTML = answer;
the following modified code should work
var taxes = {
getPercentage: function(total, payment) {
var percentage = (Math.floor((payment / total) * 100));
return percentage
},
}
var handlers = {
getPercentage: function() {
var totalInput = document.getElementById('totalInput');
var paymentInput = document.getElementById('paymentInput');
var answer = taxes.getPercentage(totalInput.value, paymentInput.value);
document.getElementById('answerParagraph').innerHTML = answer
}
}
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div id="getPercentage">
<div id="total">
Total owed:
<input id="totalInput" type="text">
</div>
<div id="payment">
Your payment:
<input id="paymentInput" type="text">
</div>
<button onclick="handlers.getPercentage()">Get percentage</button>
</div>
<div>
<p id="answerParagraph">
</p>
</div>
<script>
</script>
</body>
</html>
You can leave out the button if you trigger the calcpercentage() function by the keyup-event on either of the two input fields:
// define shorthand notation byId(id):
const byId=id=>document.getElementById(id);
// delegated event binding: affects INPUT elements only
byId('getPercentage').addEventListener('keyup',function(ev){
if(ev.target.tagName!='INPUT') return false;
byId('answerParagraph').innerHTML=
(byId('paymentInput').value*100 /
byId('totalInput').value).toFixed(2)+"%";
});
// trigger event manually ...
byId('totalInput').dispatchEvent(new Event('keyup',{bubbles:true}));
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div id="getPercentage">
<div id="total">
Total owed:
<input id="totalInput" type="text" value="1000">
</div>
<div id="payment">
Your payment:
<input id="paymentInput" type="text" value="25">
</div>
</div>
<div>
<p id="answerParagraph">
</p>
</div>
<script>
</script>
</body>
</html>
Related
I'm really new to JS. I am working on the if else statement and returning the total using the button. I also want to return some other input from HTML file also using the same button or on the same function as my calculate function. How do I return the total amount, name(input), number(input), from html to that one button as well?
If you don't get my question please run the code and see that it is not printing out the other input value. Thank you for helping me out.
function calculate() {
var total
var kwh = parseFloat(document.getElementById("kw").value);
if (kwh <= 50) {
total = (kwh * 500);
} else if (kwh <= 100) {
total = kwh * 1000;
} else {
total = kwh * 2120;
}
document.getElementById("total").innerHTML = total;
}
<body>
<div>
<label>ឈ្មោះអតិថិជន:</label>
<input id="name" type="text" placeholder="ឈ្មោះអតិថិជន">
</div>
<div>
<label>ឈ្មោះអតិថិជន:</label>
<input type="number" placeholder="លេខអតិថិជន">
</div>
<div>
<label>ឈ្មោះអតិថិជន:</label>
<input type="number" placeholder="kwh" id="kw">
</div>
<button type="button" onclick="calculate()">គណនា</button>
<p>Result: <span id="total"></span></p>
<p>Name: <span id="name"></span></p>
<!-- <script src="script2.js"></script> -->
</body>
You are very close just need a few tweaks.
You shouldn't repeat ids, so in that case, to make it easier to understand, we can rename the input with id name to name_input, so you can retrieve its value as
document.getElementById('name_input').value
You can add that to your function and assign it to the innerHTML of name inside the function calculate() and so on with as many actions as you want
Working snippet:
function calculate() {
var total
var kwh = parseFloat(document.getElementById("kw").value);
if (kwh <= 50) {
total = (kwh * 500);
} else if (kwh <= 100) {
total = kwh * 1000;
} else {
total = kwh * 2120;
}
document.getElementById("total").innerHTML = total;
document.getElementById("name").innerHTML = document.getElementById("name_input").value;
}
<body>
<div>
<label>ឈ្មោះអតិថិជន:</label>
<input id="name_input" type="text" placeholder="ឈ្មោះអតិថិជន">
</div>
<div>
<label>ឈ្មោះអតិថិជន:</label>
<input type="number" placeholder="លេខអតិថិជន">
</div>
<div>
<label>ឈ្មោះអតិថិជន:</label>
<input type="number" placeholder="kwh" id="kw">
</div>
<button type="button" onclick="calculate()">គណនា</button>
<p>Result: <span id="total"></span></p>
<p>Name: <span id="name"></span></p>
<!-- <script src="script2.js"></script> -->
</body>
I have created a tip calculator. After you put in the amount and hit enter text pops up telling you how much you owe if you pay 20%. I figured out how to clear the numbers in the <input> but I can't figure out the JS so that the text clears as well.
This is a link to my file.
https://codepen.io/wrraybin/pen/WVdvLN
<!DOCTYPE html>
<html>
<head>
<title>Tip Calculator</title>
<link href="https://fonts.googleapis.com/css?family=Indie+Flower&display=swap" rel="stylesheet">
<link rel="stylesheet" href='tip-calc.css'>
</head>
<body>
<div>
<h1>Tip Calculator</h1>
<form id='tip-calc'>
<input id='enter-num' type='number' placeholder='Bill Total' name='tipTotal' >
<div id='buttons'>
<button id='butt-one'>Tip</button>
<input id='butt-two' type="reset" value="Reset" name='resetButton'>
</div>
</form>
</div>
<div id='final-amount'>
</div>
</body>
<script src="tip-calc.js"></script>
</html>
document.querySelector('#tip-calc').addEventListener('submit', function(e){
e.preventDefault()
document.querySelector('#final-amount').innerHTML = ''
const billTotal = document.createElement('h2')
const tip = Math.floor( e.target.elements.tipTotal.value * 0.2)
billTotal.textContent = `You should leave $${tip} if tipping 20%.`
document.querySelector('#final-amount').appendChild(billTotal)
})
Add this code to file tip-calc.js
document.querySelector('#butt-two').onclick =
() => document.querySelector('#final-amount').innerHTML = '';
document.querySelector('#tip-calc').addEventListener('submit', function(e) {
e.preventDefault()
document.querySelector('#final-amount').innerHTML = ''
const billTotal = document.createElement('h2')
const tip = Math.floor(e.target.elements.tipTotal.value * 0.2)
billTotal.textContent = `You should leave $${tip} if tipping 20%.`
document.querySelector('#final-amount').appendChild(billTotal)
})
document.querySelector('#butt-two').onclick =
() => document.querySelector('#final-amount').innerHTML = '';
<div>
<h1>Tip Calculator</h1>
<form id='tip-calc'>
<input id='enter-num' type='number' placeholder='Bill Total' name='tipTotal'>
<div id='buttons'>
<button id='butt-one'>Tip</button>
<input id='butt-two' type="reset" value="Reset" name='resetButton'>
</div>
</form>
</div>
<div id='final-amount'>
</div>
Add an event listener on the reset button and on click reset the Html in the final-amount div
document.querySelector('#butt-two').addEventListener('click', function(e){
document.querySelector('#final-amount').innerHTML = ''
})
I have a function that makes use of 3 inputs. Unfortunately when i fill in all 3 the inputs. The result shows up for 1 second and goes away... But when i fill in only 2 of the 3 inputs. The result will show up, but of course is missing some of the input.
<!DOCTYPE html>
<html>
<head lang="en">
<h1> BMI Calculator</h1>
<meta charset="UTF-8">
<script src="js/jquery-3.3.1.js"></script>
<script src="js/script.js"></script>
</head>
<body>
<form>
<label><b>Lengte</b></label>
<input type="number" name="message" id="user_lengte" required><span>cm</span><br>
<label><b>Gewicht</b></label>
<input type="number" name="message" id="user_gewicht" required><span>kg</span><br>
<label><b>Leeftijd</b></label>
<input type="number" name="message" id="user_leeftijd" required><span>jr</span><br>
<button type="submit" onclick="showBMI();" value="Calculate">Berekenen</button><br/>
<label> </label><br>
<label>Your BMI: </label>
<p><span id='display'></span></p>
</form>
</body>
</html>
function showBMI() {
var gewicht = document.getElementById("user_gewicht").value;
var lengte = document.getElementById("user_lengte").value;
var leeftijd = document.getElementById("user_leeftijd").value;
document.getElementById('display').innerHTML =
(88.362 + (13.397 * gewicht) + (4.799 * lengte) - (5.677 * leeftijd)).toFixed(2)
//88.362 + ( 13.397 x weight in kg ) + ( 4.799 x height in cm ) - ( 5.677 x age in years )
};
I would like to be able to fill in all 3 the inputs and have it displayed.
Since you have a button type as submit, the default behaviour of it is to submit the form and force refresh of the page, which you can disable by passing the event to showBMI method and using event.preventDefault();
function showBMI(e) {
e.preventDefault();
var gewicht = document.getElementById("user_gewicht").value;
var lengte = document.getElementById("user_lengte").value;
var leeftijd = document.getElementById("user_leeftijd").value;
document.getElementById('display').innerHTML =
(88.362 + (13.397 * gewicht) + (4.799 * lengte) - (5.677 * leeftijd)).toFixed(2)
//88.362 + ( 13.397 x weight in kg ) + ( 4.799 x height in cm ) - ( 5.677 x age in years )
};
<!DOCTYPE html>
<html>
<head lang="en">
<h1> BMI Calculator</h1>
<meta charset="UTF-8">
<script src="js/jquery-3.3.1.js"></script>
<script src="js/script.js"></script>
</head>
<body>
<form>
<label><b>Lengte</b></label>
<input type="number" name="message" id="user_lengte" required><span>cm</span><br>
<label><b>Gewicht</b></label>
<input type="number" name="message" id="user_gewicht" required><span>kg</span><br>
<label><b>Leeftijd</b></label>
<input type="number" name="message" id="user_leeftijd" required><span>jr</span><br>
<button type="submit" onclick="showBMI(event);" value="Calculate">Berekenen</button><br/>
<label> </label><br>
<label>Your BMI: </label>
<p><span id='display'></span></p>
</form>
</body>
</html>
Change button type to "button"
<button type="button" onclick="showBMI();" value="Calculate">Berekenen</button><br/>
function showBMI() {
var gewicht = document.getElementById("user_gewicht").value;
var lengte = document.getElementById("user_lengte").value;
var leeftijd = document.getElementById("user_leeftijd").value;
document.getElementById('display').innerHTML =
(88.362 + (13.397 * gewicht) + (4.799 * lengte) - (5.677 * leeftijd)).toFixed(2)
//88.362 + ( 13.397 x weight in kg ) + ( 4.799 x height in cm ) - ( 5.677 x age in years )
};
$(document).on('click', '#showBMI', function (e) {
showBMI();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<head lang="en">
<h1> BMI Calculator</h1>
<meta charset="UTF-8">
</head>
<body>
<form>
<label><b>Lengte</b></label>
<input type="number" name="message" id="user_lengte" required><span>cm</span><br>
<label><b>Gewicht</b></label>
<input type="number" name="message" id="user_gewicht" required><span>kg</span><br>
<label><b>Leeftijd</b></label>
<input type="number" name="message" id="user_leeftijd" required><span>jr</span><br>
<button id="showBMI" value="Calculate">Berekenen</button><br/>
<label> </label><br>
<label>Your BMI: </label>
<p><span id='display'></span></p>
</form>
</body>
</html>
function showBMI() {
var gewicht = document.getElementById("user_gewicht").value;
var lengte = document.getElementById("user_lengte").value;
var leeftijd = document.getElementById("user_leeftijd").value;
document.getElementById('display').innerHTML =
(88.362 + (13.397 * gewicht) + (4.799 * lengte) - (5.677 * leeftijd)).toFixed(2)
//88.362 + ( 13.397 x weight in kg ) + ( 4.799 x height in cm ) - ( 5.677 x age in years )
};
$(document).on('click', '#showBMI', function (e) {
showBMI();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<head lang="en">
<h1> BMI Calculator</h1>
<meta charset="UTF-8">
</head>
<body>
<form>
<label><b>Lengte</b></label>
<input type="number" name="message" id="user_lengte" required><span>cm</span><br>
<label><b>Gewicht</b></label>
<input type="number" name="message" id="user_gewicht" required><span>kg</span><br>
<label><b>Leeftijd</b></label>
<input type="number" name="message" id="user_leeftijd" required><span>jr</span><br>
<button id="showBMI" value="Calculate">Berekenen</button><br/>
<label> </label><br>
<label>Your BMI: </label>
<p><span id='display'></span></p>
</form>
</body>
</html>
You need to add onsubmit event to the form tag
<form onsubmit="return false">
Then it will be good to remove onclick event from submit button and call showBMI() method to onsubmit event like this:
<form onsubmit="showBMI(); return false">
I have two buttons in my form for calling two JavaScript functions. The first button works good in its onclick event calling the payroll() function successfully but the second button is of type submit and it never calls the send() function on form submission. I don't know why this issue occurs.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!DOCTYPE html>
<html >
<head>
<title>hr page</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript"
src="/static/js/sijax/sijax.js"></script>
<script type="text/javascript">
{{ g.sijax.get_js()|safe }}</script>
<link rel="stylesheet" href="{{url_for('static', filename='styles/signupcss.css')}}">
<script type="text/javascript" >
function payroll() {
var basic=document.forms["salary"]["bsalary"].value;
var empid=document.forms["salary"]["empid"].value;
var ta,hra,da,pf,netsalary,grosssalary;
if (empid == ""||basic == "") {
alert("Employee ID and Salary details must be filled out");
return false;
}
if(isNaN(basic))
{alert("Salary must be in Numbers");
return false;
}
hra=basic*40/100;
da=basic*15/100;
pf=basic*12/100;
basic=parseInt(basic);
hra=parseInt(hra);
da=parseInt(da);
grosssalary=basic + hra + da;
ta=basic*6.2/100;
netsalary=grosssalary-ta;
document.getElementById("hra").innerHTML=hra;
document.getElementById("ta").innerHTML=ta;
document.getElementById("da").innerHTML=da;
document.getElementById("netsalary").innerHTML=netsalary;
document.getElementById("pf").innerHTML=pf;
document.getElementById("grosssalary").innerHTML=grosssalary;
window.alert("HI"+grosssalary);
return true;
}
function send()
{
var id = document.forms['salary']['empid'].value;
var basic = document.forms['salary']['bsalary'].value;
var hra = document.forms['salary']['hra'].value;
var da = document.forms['salary']['da'].value;
var ta = document.forms['salary']['ta'].value;
var pf = document.forms['salary']['pf'].value;
var gross_sal = document.forms['salary']['grosssalary'].value;
window.alert("HI"+gross_sal);
var net_sal = document.forms['salary']['netsalary'].value;
Sijax.request('send',[id, basic, hra, ta, da, pf, gross_sal, net_sal]);
}
</script>
</head>
<body style="font-family:Lato">
<div style="padding-left:5%;padding-top:0.2%;height:1%;width:100%;background-color:#11557c">
<h2>Welcome to HR Department</h2><br>
</div>
<div style="margin-left:15%" >
<h2>Name</h2>
<form id="salary" name="salary" style="margin-top: 2%" method="post" onsubmit="return send()" >
<label id = "empid">Employee ID</label><br>
<input type = "text" name = "empid" placeholder = "Employee ID" /><br><br>
<label id = "bsalary">Basic Salary</label><br>
<input type = "text" name = "bsalary" placeholder = "Basic salary" /><br><br>
<input type="button" value="Calculate" onclick="return payroll()"><br><br>
<label for ="hra">House Rent Allowance(HRA)</label>
<p id="hra" name="hra"></p><br>
<label for ="ta">Travel Allowance(TA)</label>
<p id="ta" name="ta"></p><br>
<label for ="da"> Dearness Allowance(DA)</label>
<p id="da" name="da"></p><br>
<label for ="netsalary">Net Salary</label>
<p id="netsalary" name="netsalary"></p><br>
<label for ="pf">Provident Fund(PF)</label>
<p id="pf" name ="pf"></p><br>
<label for ="grosssalary">Gross Salary</label>
<p id="grosssalary" name="grosssalary"></p><br><br>
<input type="submit" value="Upload Salary">
</form>
</div>
</body>
</html>
You can't act with <p> elements like as a form-elements. You may create a respective <input type="hidden"> elements and fill them in payroll(), or get values by .innerHtml on paragraphs.
P.S. You have actually a TypeError exception, calling undeclared form elements like document.forms['salary']['grosssalary'] and so on.
okay, quick fix, since you are using python flask library Sijax for ajax and therefore jQuery, you can alter your javascript send function like this:
function send(e){
e.preventDefault(); //it is as good as returning
//false from the function in all cases
var id = document.forms['salary']['empid'].value;
...
}
and change your onsubmit handler declaration like this:
<form id="salary" name="salary" style="margin-top: 2%" method="post"
onsubmit="return send(event)" >
please note that when you stop the event chain propagation, you will have to do a manual submission of the form.
So, you can modify your send function to do .preventDefault based on your custom criterias, otherwise, let the form submit
Your code actually works, if you're running this code as a snippet here in stack overflow, Form submission is actually blocked by default. Try running your code in codepen. I tried it and it's actually working.
http://codepen.io/jhonix22/pen/VPZagb
Check this out. It is nowhere close to a perfect solution but I think it helps. You can not access the paragraphs as if you would the form input elements. Im not entirely sure what Sijax thing is. I believe it is just a normal AJAX HTTP thing with some sort of CSRF security filters.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!DOCTYPE html>
<html>
<head>
<title>hr page</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript"
src="/static/js/sijax/sijax.js"></script>
<script type="text/javascript">
{
{
g.sijax.get_js() | safe
}
}</script>
<link rel="stylesheet" href="{{url_for('static', filename='styles/signupcss.css')}}">
<script type="text/javascript">
function payroll() {
var basic = document.forms["salary"]["bsalary"].value;
var empid = document.forms["salary"]["empid"].value;
var ta, hra, da, pf, netsalary, grosssalary;
if (empid == "" || basic == "") {
alert("Employee ID and Salary details must be filled out");
return false;
}
if (isNaN(basic)) {
alert("Salary must be in Numbers");
return false;
}
hra = basic * 40 / 100;
da = basic * 15 / 100;
pf = basic * 12 / 100;
basic = parseInt(basic);
hra = parseInt(hra);
da = parseInt(da);
grosssalary = basic + hra + da;
ta = basic * 6.2 / 100;
netsalary = grosssalary - ta;
document.getElementById("hra").innerHTML = hra;
document.getElementById("ta").innerHTML = ta;
document.getElementById("da").innerHTML = da;
document.getElementById("netsalary").innerHTML = netsalary;
document.getElementById("pf").innerHTML = pf;
document.getElementById("grosssalary").innerHTML = grosssalary;
window.alert("HI" + grosssalary);
return true;
}
function send() {
var id = document.forms['salary']['empid'].value;
var basic = document.forms['salary']['bsalary'].value;
var hra = document.getElementById('hra').innerHTML;
var da = document.getElementById('da').innerHTML;
var ta = document.getElementById('ta').innerHTML;
var pf = document.getElementById('pf').innerHTML;
var gross_sal = document.getElementById('grosssalary').innerHTML;
window.alert("HI" + gross_sal);
var net_sal = document.getElementById('netsalary').innerHTML;
// I think you are missing something here.
Sijax.request('send', [id, basic, hra, ta, da, pf, gross_sal, net_sal]);
}
</script>
</head>
<body style="font-family:Lato">
<div style="padding-left:5%;padding-top:0.2%;height:1%;width:100%;background-color:#11557c">
<h2>Welcome to HR Department</h2><br>
</div>
<div style="margin-left:15%">
<h2>Name</h2>
<form id="salary" name="salary" style="margin-top: 2%" method="post" onsubmit="return false">
<label id="empid">Employee ID</label><br>
<input type="text" name="empid" placeholder="Employee ID"/><br><br>
<label id="bsalary">Basic Salary</label><br>
<input type="text" name="bsalary" placeholder="Basic salary"/><br><br>
<input type="button" value="Calculate" onclick="return payroll()"><br><br>
<label for="hra">House Rent Allowance(HRA)</label><br>
<p id="hra" readonly name="hra"></p>
<label for="ta">Travel Allowance(TA)</label><br>
<p id="ta" readonly name="ta"></p>
<label for="da"> Dearness Allowance(DA)</label><br>
<p id="da" readonly name="da"></p>
<label for="netsalary">Net Salary</label><br>
<p id="netsalary" readonly name="netsalary"></p>
<label for="pf">Provident Fund(PF)</label><br>
<p id="pf" readonly name="pf"></p>
<label for="grosssalary">Gross Salary</label><br>
<p id="grosssalary" readonly name="grosssalary"></p><br>
<input type="button" onclick="send()" value="Upload Salary">
</form>
</div>
</body>
</html>
I'm writing a JS code to calculate a final grade given some individual grades and output the result in the html page but when I trigger the event and function it outputs a wrong answer for a split second then immediately disappears along with the values entered into the text box.
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Problem 2</title>
<script src="grades.js" type="text/javascript"></script>
</head>
<body>
<h1>Grade Calculator</h1>
<form id ="myForm">
<div id="assignments">
HW <input type="text" size="1"/> / <input type="text" size="1"/><br/>
HW <input type="text" size="1"/> / <input type="text" size="1"/><br/>
HW <input type="text" size="1"/> / <input type="text" size="1"/>
</div>
<div>
<input type="checkbox" /> Curve +5?
</div>
<div id="resultsarea">
<p>
<!--add buttons here -->
<button id="comp">Compute</button>
<button id="clr">Clear</button>
</p>
<!-- add results here -->
</div>
</form>
</body>
</html>
JS:
window.onload = pageLoad;
function pageLoad()
{
var cbutton = document.getElementById("comp");
cbutton.onclick = compute;
}
function compute()
{
var values = document.getElementsByTagName("input");
var marks = 0;
var total = 0;
for (var i=0; i < values.length; i++)
{
if(values[i].type == "text")
{
if (i%2 == 0)
marks += parseInt(values[i].value);
else
total += parseInt(values[i].value);
}
}
var result = Math.round(marks/total);
document.writeln(result);
}