How to use multiple button for same function in javascript? - javascript

I am new in javascript. I want to create multiple button with same function and result will be shown in same place. From my code I want to change tip1 value for every button click event. How can I do this? Please help me if any one have any idea.
My codes are below:
<form id="calculator">
<p>Amount: <input id="amount" /></p>
<p>Years: <input id="year" /></p>
<hr />
<p>Tip: <input id="tip" disabled="disabled" /></p>
<p>Total: <input id="total" disabled="disabled" /></p>
<button onclick="calculate()" id="1">Button1</button>
<button onclick="calculate1()" id="2">Button2</button>
</form>
<script type="text/javascript">
function calculate () {
var amount = $('#amount').val();
var year = $('#year').val();
if (button 1) {
var tip1 = (1 + 115 / 100);
}
else if (button 2) {
var tip1 = (1 + 215 / 100);
}
var tip = Math.pow(tip1, year);
var total = amount * tip;
$('#tip').val( tip.toFixed(2) );
$('#total').val( total.toFixed(2) );
return false;
}
$('#calculator').submit( calculate );
</script>

You can do it like this:
function calculateF(target) {
var amount = parseFloat($('#amount').val());
var year = parseFloat($('#year').val());
if (target == 1) {
var tip1 = (1 + 115 / 100);
} else if (target == 2) {
var tip1 = (1 + 215 / 100);
}
var tip = Math.pow(tip1, year);
var total = amount * tip;
$('#tip').val(tip.toFixed(2));
$('#total').val(total.toFixed(2));
return false;
}
$('button').click(function(e) {
calculateF($(e.target).prop('id'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<p>Amount: <input id="amount" /></p>
<p>Years: <input id="year" /></p>
<hr />
<p>Tip: <input id="tip" disabled="disabled" /></p>
<p>Total: <input id="total" disabled="disabled" /></p>
<button id="1">Button1</button>
<button id="2">Button2</button>

Also, by passing ID directly
function calculate (id) {
var amount = $('#amount').val();
var year = $('#year').val();
var tip1 = 0;
if (id == "1") {
tip1 = (1 + 115 / 100);
}
else if (id == "2") {
tip1 = (1 + 215 / 100);
}
var tip = Math.pow(tip1, year);
var total = amount * tip;
$('#tip').val( tip.toFixed(2) );
$('#total').val( total.toFixed(2) );
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Amount: <input id="amount" /></p>
<p>Years: <input id="year" /></p>
<hr />
<p>Tip: <input id="tip" disabled="disabled" /></p>
<p>Total: <input id="total" disabled="disabled" /></p>
<button onclick="calculate(this.id)" id="1">Button1</button>
<button onclick="calculate(this.id)" id="2">Button2</button>

You are declaring var tip1 at wrong places.
Just Use this to call the function calculate(id).
$('button').click(function(e) {
calculate(this.id);
});
HTML
<form id="calculator">
<p>Amount: <input id="amount" /></p>
<p>Years: <input id="year" /></p>
<hr />
<p>Tip: <input id="tip" disabled="disabled" /></p>
<p>Total: <input id="total" disabled="disabled" /></p>
<button id="1">Button1</button>
<button id="2">Button2</button>
</form>
calculate() function
function calculate () {
var amount = $('#amount').val();
var year = $('#year').val();
var tip1;
if (id=="1") {
tip1 = (1 + 115 / 100);
}
else if (id=="2") {
tip1 = (1 + 215 / 100);
}
var tip = Math.pow(tip1, year);
var total = amount * tip;
$('#tip').val( tip.toFixed(2) );
$('#total').val( total.toFixed(2) );
return false;
}

Related

How to calculate tax in salary

I am working on a payroll project in which I want to calculate overtime, allowance and tax to salary. I want to add overtime and allowance to salary and subtract tax from salary.
The following script works with overtime and allowance but I'm facing problems with calculating tax.
When I enter a tax percentage it should calculate the tax amount from the salary to the tax field and calculate the total. When I enter the tax directly it should calculate the percentage to the taxPercentage field and calculate the total.
$(document).on('change keyup blur', '.add', function(e) {
add();
});
function add() {
salary = $('#salary').val();
allowance = $('#allowance').val() || 0;
over = $('#over').val() || 0;
prevTotal = $('#total').val() || 9000;
if (allowance > 0 || over > 0) {
total = parseFloat(salary) + parseFloat(allowance) + parseFloat(over);
$('#total').val(total);
} else {
$('#total').val(prevTotal);
}
}
$(document).on('change keyup blur', '.tax', function(e) {
subtracttax();
});
function subtracttax() {
salary = $('#salary').val();
taxPercentage = $('#taxPercentage').val() || 0;
tax = $('#tax').val() || 0;
prevTotal = $('#total').val() || 9000;
if (taxPercentage > 0) {
total = parseFloat(salary) * parseFloat(taxPercentage) / 100;
$('#tax').val(total);
$('#total').val(prevTotal - total);
} else {
$('#total').val(prevTotal);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<div>
<label> salary </label>
<input type="text" id="salary" value="9000" />
</div>
<br>
<div>
<label> over Time </label>
<input type="text" class="add" id="over" />
</div>
<br>
<div>
<label> allowance </label>
<input type="text" class="add" id="allowance" />
</div>
<br>
<div>
<label> Tax Percentage</label>
<input type="text" class="tax" id="taxPercentage" />
</div>
<br>
<div>
<label> Total Tax</label>
<input type="text" class="tax" id="tax" />
</div>
<br>
<div>
<label> Total salary</label>
<input type="text" id="total" />
</div>
Try like this.
as per your comment I only added salary + over time.
calculateTax();
$(document).on('change keyup blur', '.tax', function(e) {
calculateTax();
});
$(document).on('change keyup blur', '.taxVal', function(e) {
calculateTaxPer();
});
function calculateTax() {
salary = $('#salary').val();
allowance = $('#allowance').val() || 0;
over = $('#over').val() || 0;
total = (parseFloat(salary) + parseFloat(allowance) + parseFloat(over)) || 0;
taxPercentage = $('#taxPercentage').val() || 0;
tax = $('#tax').val() || 0;
$('#total').val(total);
if (taxPercentage > 0) {
totalTax = (parseFloat(salary) + parseFloat(over)) * parseFloat(taxPercentage) / 100;
$('#tax').val(totalTax);
$('#total').val(total - totalTax);
return false;
}
}
function calculateTaxPer(){
salary = $('#salary').val();
allowance = $('#allowance').val() || 0;
over = $('#over').val() || 0;
total = (parseFloat(salary) + parseFloat(allowance) + parseFloat(over)) || 0;
taxPercentage = $('#taxPercentage').val() || 0;
tax = $('#tax').val() || 0;
$('#total').val(total);
if(tax > 0){
taxPer = (parseFloat(tax)/(parseFloat(salary) + parseFloat(over)))*100;
$('#taxPercentage').val(taxPer);
$('#total').val(total - tax);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<div>
<label> salary </label>
<input type="text" id="salary" value="9000" />
</div>
<br>
<div>
<label> over Time </label>
<input type="text" class="tax" id="over" />
</div>
<br>
<div>
<label> allowance </label>
<input type="text" class="tax" id="allowance" />
</div>
<br>
<div>
<label> Tax Percentage</label>
<input type="text" class="tax" id="taxPercentage" />
</div>
<br>
<div>
<label> Total Tax</label>
<input type="text" class="taxVal" id="tax" />
</div>
<br>
<div>
<label> Total salary</label>
<input type="text" id="total" />
</div>
change this line in subtracttax function
prevTotal = $('#total').val() || 9000;
to
prevTotal = parseFloat(salary) + parseFloat(allowance) + parseFloat(over);
Problem is you are overriding the total value once the tax value is entered. Instead you should calculate totals each time you make changes.

Simple js calculator with radio tag

I found subjects like mine but I could not fix my problem. So I wanted to calculate the cost of tickets form radio tags by multiplying the price with the amount of tickets using if statements for each option without jquery. I can not figure it out why I do not have an output. It looks like none of my functions work and I can not find why.
Can you help me please, I know it is easy but I am still a beginner
<!doctype html>
<html>
<head>
<title>No Boundaries</title>
<link rel="stylesheet" href="styles1.css">
<script type="text/javascript">
function validate(){
if(!document.form1.cond.checked)
{alert("Please accept the Terms and Conditions");
return false;
}
if(document.form1.name.value.length < 2)
{alert(“Please enter your full name, not just an initial”);
return false;
}
return true;
}
function cost() {
if (document.form1.accom["v"].checked) {
var amount = parseInt(document.form1.amount.value);
var ans = 90 * amount;
document.form1.total1.value = ans;
}
else if (document.form1.accom["t"].checked) {
var amount = parseInt(document.form1.amount.value);
var ans = 150 * amount;
document.form1.total1.value = ans;
}
else if (document.form1.accom["c"].checked) {
var amount = parseInt(document.form1.amount.value);
var ans = 45 * amount;
document.form1.total1.value = ans;
}
}
function post(){
if(document.form1.del["1"].checked){
var num = 0;
var ans = num;
document.form1.total2.value = ans;
}
if(document.form1.del["2"].checked){
var num = 12;
var ans = num;
document.form1.total2.value = ans;
}
if(document.form1.del["3"].checked){
var num = 16;
var ans = num;
document.form1.total2.value = ans;
}
if(document.form1.del["4"].checked){
var num = 20;
var ans = num;
document.form1.total2.value = ans;
}
}
function damage(){
var total1 = parseInt(document.form1.total1.value);
var total1 = parseInt(document.form1.total1.value);
var ans = total1 + total2;
document.form.total3.value = ans;
}
</script>
</head>
<body>
<section>
<form name="form1">
<fieldset>
<legend>Personal details</legend>
<div>
Please enter your full name<br>
<input name="name" type="text" required onsubmit="return validate();"><br>
</div>
<div>
Address<br>
<input name="addresss" type="text" required><br>
<input type="text"><br>
<input type="text"><br>
<input type="text"><br>
</div>
<div>
Phone Number<br>
<input name="phone" type="tel"><br>
</div>
<div>
Email Address<br>
<input name="email" type="email" required><br>
</div>
<div>
Date of Birth<br>
<input name="birth" type="date"><br>
</div>
</fieldset>
<fieldset>
<legend>Ticket Details</legend>
<div>
Type of T<br>
<label for="vil">V</label>
<input type="radio" name="accom[]" value="v">
<label for="town">T</label>
<input type="radio" name="accom[]" value="t">
<label for="con">C</label>
<input type="radio" name="accom[]" value="c">
</div>
<div>
Quantity of T
<input name="amount" type="number" min="1" max="10" required><br>
<br>
<input type="button" name="cost" value="C C" onclick="cost();"><br>
</div>
<div>
Delivery Options<br>
<input type="radio" name="del[]" value="1" >Free<br>
<input type="radio" name="del[]" value="2" >£12<br>
<input type="radio" name="del[]" value="3" >£16<br>
<input type="radio" name="del[]" value="4" >£20<br>
<br>
<input type="button" value="C D" onclick="post();"><br>
</div>
</fieldset>
<fieldset>
<legend>Terms And Conditions</legend>
<input name="cond" type="checkbox" onsubmit="return validate();">
</fieldset>
<fieldset>
<legend>Cost</legend>
<input type="text" name="total1" readonly><br>
<input type="text" name="total2" readonly><br>
<input type="text" name="total3" readonly><br>
<br>
<input type="button" value="C F C" onclick="damage();"><br>
</fieldset>
<br><br>
<fieldset>
<input type="submit">
</fieldset>
</form>
</section>
</body>
</html>
the cost function should be something like this,
function cost() {
if (document.form1.accom.value.toLowerCase() == "v") {
var amount = parseInt(document.form1.amount.value);
var ans = 90 * amount;
document.form1.total1.value = ans;
} else if (document.form1.accom.value.toLowerCase() == "t") {
var amount = parseInt(document.form1.amount.value);
var ans = 150 * amount;
document.form1.total1.value = ans;
} else if (document.form1.accom.value.toLowerCase() == "c") {
var amount = parseInt(document.form1.amount.value);
var ans = 45 * amount;
document.form1.total1.value = ans;
}
}
And to make the code more refactored, make it like this,
function cost() {
var val = document.form1.accom.value.toLowerCase();
var amount = parseInt(document.form1.amount.value);
var ans;
if (val == "v") {
ans = 90 * amount;
} else if (val == "t") {
ans = 150 * amount;
} else if (val == "c") {
ans = 45 * amount;
}
document.form1.total1.value = ans;
}
Ok I found your errors. This is the code for html
<div>
Type of T<br>
<label for="vil">V</label>
<input type="radio" name="accom" value="v">
<label for="town">T</label>
<input type="radio" name="accom" value="t">
<label for="con">C</label>
</div>
<div>
Quantity of T
<input name="amount" type="number" min="1" max="10" required><br>
<br>
<input type="button" name="cost" value="C C" onclick="costs();"><br>
</div>
Next, in your javascript you have tho change the name of function; instead of cost you have to renaming in costs
function costs() {
if (document.form1.accom.value == 'v') {
var amount = parseInt(document.form1.amount.value);
var ans = 90 * amount;
document.form1.total1.value = ans;
}
else if (document.form1.accom.value == 't') {
var amount = parseInt(document.form1.amount.value);
var ans = 150 * amount;
document.form1.total1.value = ans;
}
else if (document.form1.a`enter code here`ccom.value == 'c') {
var amount = parseInt(document.form1.amount.value);
var ans = 45 * amount;
document.form1.total1.value = ans;
}
}
That's all

Form with radio buttons and one input field. Calculate the value depending on radio button selcted

I would like to convert the temperature given in Celsius to Fahrenheit degrees or the other way round. I would like the unit to be chosen via radio button form and the converted units calculated with JS function. However, I am doing something wrong, and I am not sure what exactly. Any help would be appreciated. Thanks.
<body>
<p>Convert temperatures to and from celsius, fahrenheit.</p>
<p id="myForm>
<form name="units" onsubmit="return convertTemp();" method="post">
<input type="number" id="temp"><br>
Temperature in:
<fieldset>
<input type="radio" name="Temperature" id="c" value="c" checked><label for="c">Celsius degrees</label>
<input type="radio" name="Temperature" id="f" value="f"><label for="f">Fahrenheit degrees</label>
</fieldset>
<input type="submit" value="Oblicz">
<form>
</p>
<p id="wynik"></p>
And here is my JavaScript function:
function convertTemp() {
alert("Włączyła się");
var x = document.Jednostki.Temperature.value;
if (x == "c"){
alert("Celsjusz");
}
else if (x == "f"){
alert("Fahrenheit");
}
returns false;
}
Here is what I would suggest
window.addEventListener("load", function() {
document.getElementById("units").addEventListener("submit", function(e) {
e.preventDefault();
console.log("Włączyła się");
var num = parseInt(document.getElementById("temp").value, 10);
if (document.getElementById("c").checked) {
console.log("Celsjusz");
document.getElementById("wynik").innerHTML = num + "C," + (Math.round(num * 9 / 5) + 32) + "F";
} else if (document.getElementById("f").checked) {
console.log("Fahrenheit");
document.getElementById("wynik").innerHTML = num + "F," + (Math.round((num - 32) * 5 / 9)) + "C";
}
});
});
<p>Convert temperatures to and from celsius, fahrenheit.</p>
<p>
<form id="units">
<input type="number" id="temp"><br> Temperature in:
<fieldset>
<input type="radio" name="Temperature" id="c" value="c" checked><label for="c">Celsius degrees</label>
<input type="radio" name="Temperature" id="f" value="f"><label for="f">Fahrenheit degrees</label>
</fieldset>
<input type="submit" value="Oblicz">
<form>
</p>
<p id="wynik"></p>
Using querySelector:
window.addEventListener("load", function() {
document.getElementById("units").addEventListener("submit", function(e) {
e.preventDefault();
console.log("Włączyła się");
const num = parseInt(document.getElementById("temp").value, 10);
const type = document.querySelector("[name=Temperature]:checked").value;
if (type==="c") {
console.log("Celsjusz");
document.getElementById("wynik").innerHTML = num + "C," + (Math.round(num * 9 / 5) + 32) + "F";
} else {
console.log("Fahrenheit");
document.getElementById("wynik").innerHTML = num + "F," + (Math.round((num - 32) * 5 / 9)) + "C";
}
});
});
<p>Convert temperatures to and from celsius, fahrenheit.</p>
<p>
<form id="units">
<input type="number" id="temp"><br> Temperature in:
<fieldset>
<input type="radio" name="Temperature" id="c" value="c" checked><label for="c">Celsius degrees</label>
<input type="radio" name="Temperature" id="f" value="f"><label for="f">Fahrenheit degrees</label>
</fieldset>
<input type="submit" value="Oblicz">
<form>
</p>
<p id="wynik"></p>
First issue I see: returns false; should be return false; (no s).
You should also retrieve the values using document.getElementById():
function convertTemp() {
alert("Włączyła się");
var celsius = document.getElementById('c');
var fahr = document.getElementById('f');
if (c.checked){
alert("Celsjusz");
}
else{
alert("Fahrenheit");
}
return false;
}
document.getElementById("units").onsubmit = convertTemp;
using jquery you can do it raplce this line
var x = document.Jednostki.Temperature.value;
to
var x = $('input[name="Temperature"]:checked').val()
you can see it working here
to get jquery click here

Change value of input box based on selected item and other value

So basically, I am creating an application form for gym membership.
The base cost is $100. If juggling is selected, the cost will increase by $50.
Also, the base cost will increase by $50 if the 'BMI' is > 25 and <= 30. If the 'BMI' is > 30, it will increase by $100 instead.
This is my code. It is not working as intended. Would like some help. Thanks a lot.
<!DOCTYPE html>
<html>
<head>
<title>UWS application form</title>
<link rel="stylesheet" href="Prac1Task2.css" />
</head>
<body>
<form>
<fieldset>
<legend>Fitness Details</legend>
Favourite Activities: <br/>
<input type="checkbox" name="activity" value="cycling" id="cycling"><label for="cycling">Cycling</label>
<input type="checkbox" name="activity" value="50" id="juggling" onchange="update(this);"><label for="juggling">Juggling</label>
<br/>
<br/>
<label for="height">What is your height (Meters)</label><br/>
<input type="number" name="height" id="height" class="input" onchange="getBMI()">
<br/>
<label for="weight">What is your weight? (kg)</label><br/>
<input type="number" name="weight" id="weight" class="input" onchange="getBMI()">
<br/>
<label for="bmi">BMI:</label><br/>
<input type="number" name="bmi" id="bmi" class="input" value="" readonly>
<script>
function getBMI()
{
var height = document.getElementById("height").value;
var weight = document.getElementById("weight").value;
document.getElementById("bmi").value = (weight / height) / height;
var bmi = document.getElementById("bmi");
var price = document.getElementById("price").value;
if (bmi.value > 25 && bmi.value <= 30)
{
parseInt(price.value) += parseInt(50);
document.getElementById('price').value = price.value;
}
else if (bmi.value > 30)
{
document.getElementById("price").value = document.getElementById("price").value + 100;
}
}
</script>
</fieldset>
<br/>
<fieldset>
<legend>Application Details</legend>
Date of Application:<br/>
<input class="input" id="date" name="date" readonly />
<script>
var timetime = new Date();
document.getElementById("date").value = (timetime.getDate() + "/" + (timetime.getMonth() + 1)
+ "/" + timetime.getFullYear());
</script>
<br/><br/>
Cost of Application: <br/>
$<input type="number" class="input" id="price" name="price" step="0.01" value="100" readonly />
<script>
var total = 100;
function update(feature) {
if(feature.checked == true){
total += parseInt(feature.value);
document.getElementById('price').value = total;
}
if(feature.checked == false){
total -= parseInt(feature.value);
document.getElementById('price').value = total;
}
}
</script>
</fieldset>
<br/>
<input type="submit" value="Submit" class="button">
</form>
</body>
</html>
You haven't mentioned the exact issue which you are facing. However, I think there should be some problem with this line of code.
parseInt(price.value) += parseInt(50);
parseInt() is a function and you cannot assign values to it.
It should be some thing like this
price.value = parseInt(price.value) + parseInt(50);
Also price.value is not a proper reference because you are assigning document.getElementById("price").value; to it. So you should be using price instead of price.value

How to check to make sure a radio button is selected

I have a form that I need to figure out the code on how to make sure a radio button is selected
Here is the form
<body>
<div id="content">
<p>Enter the values below and click "Calculate".</p>
<label for="length">Length:</label>
<input type="text" id="length" /><br />
<label for="width">Width:</label>
<input type="text" id="width" /><br />
<label for="answer">Answer:</label>
<input type="text" id="Answer" disabled="disabled" /><br />
<input type="radio" name="Area" value="Area" check="checked"/>Area<br />
<input type="radio" name="Parimeter" value="Parimeter" />Parimeter<br />
<label> </label>
<input type="button" id="calculate" value="Calculate" /><br />
</div>
</body>
</html>
here is the code
var $ = function (id) {
return document.getElementById(id);
}
var calculate_click = function () {
var length = parseFloat( $("length").value );
var width = parseFloat( $("width").value );
// $("area").value = "";
if (isNaN(length) || length <= 0) {
alert("Length must be a valid number\nand greater than zero.");
} else if(isNaN(width) || width <= 0) {
alert("Width must be a valid number\nand greater than zero.");
}
} else {
var area = width * length;
var perimeter = 2 * width + 2 * length;
$("area").value = area.toFixed(2);
$("perimeter").value = perimeter.toFixed(2);
}
}
window.onload = function () {
$("calculate").onclick = calculate_click;
$("length").focus();
}
Here are some links that may help you finish your homework:
http://www.w3schools.com/html/html_forms.asp
http://www.w3schools.com/jquery/default.asp
http://jsfiddle.net

Categories