I'm getting undefined of my variable 'base' which is basic $('slider').value. I have added a console.log(base) to test what is returned, but the value is undefined.
Here is my html:
jQuery(document).ready(function($) {
let precentage = 17.5;
let commision = 0.2746;
function cost() {
let base = $('#slider').value;
let precentAmout = base * (precentage / 365 * 30);
let commisionAmout = base * commision;
let totalCost = commisionAmout + precentAmout;
let totalSum = base + commisionAmout + precentAmout;
console.log(base);
$('#cost').text(totalCost);
$('#sum').text(totalSum);
}
$('#slider').on('change', function() {
$('#amout').text(this.value);
cost();
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="calc">
<div class="range-title">
<h2 class="range-label">Ile chcesz pożyczyć?</h2>
<div class="display-wrap">
<span id="amout">500</span><span class="currency"> zł</span>
</div>
</div>
<div class="range-wrap">
<button class="buttons-change-value">-</button>
<input id="slider" class="range-input" type="range" min="500" max="1500" step="50" value="500">
<button class="buttons-change-value">+</button>
</div>
<div class="summary-container">
<div class="summary-box">
<h3>Koszt:<br>
<span id="cost">200</span><span class="currency"> zł</span></h3>
</div>
<div class="summary-box">
<h3>Do zwrotu:<br>
<span id="sum">200</span><span class="currency"> zł</span></h3>
</div>
<div class="summary-box">
<h3>RRSO:<br>
<span id="rrso">200</span><span class="percentage"> %</span></h3>
</div>
</div>
</div>
Do You have an idea why this is happening?
In JQuery, .val() function is available to get value of textbox.
let base = $('#slider').val()
jQuery(document).ready(function($) {
let precentage = 17.5;
let commision = 0.2746;
function cost() {
let base = $('#slider').val();
let precentAmout = base * (precentage / 365 * 30);
let commisionAmout = base * commision;
let totalCost = commisionAmout + precentAmout;
let totalSum = base + commisionAmout + precentAmout;
console.log(base);
$('#cost').text(totalCost);
$('#sum').text(totalSum);
}
$('#slider').on('change', function() {
$('#amout').text(this.value);
cost();
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="calc">
<div class="range-title">
<h2 class="range-label">Ile chcesz pożyczyć?</h2>
<div class="display-wrap">
<span id="amout">500</span><span class="currency"> zł</span>
</div>
</div>
<div class="range-wrap">
<button class="buttons-change-value">-</button>
<input id="slider" class="range-input" type="range" min="500" max="1500" step="50" value="500">
<button class="buttons-change-value">+</button>
</div>
<div class="summary-container">
<div class="summary-box">
<h3>Koszt:<br>
<span id="cost">200</span><span class="currency"> zł</span></h3>
</div>
<div class="summary-box">
<h3>Do zwrotu:<br>
<span id="sum">200</span><span class="currency"> zł</span></h3>
</div>
<div class="summary-box">
<h3>RRSO:<br>
<span id="rrso">200</span><span class="percentage"> %</span></h3>
</div>
</div>
</div>
jQuery objects don't have a value property, they have a val() method.
You can always pass the base variable value as a parameter to the cost function like this cost(this.value). That would make more sense since you are already fetching the slider value once via onChange no need to do it again inside the cost function.
Please take a look at the working snippet below.
jQuery(document).ready(function ($) {
let precentage = 17.5;
let commision = 0.2746;
function cost(sliderValue) {
let base = sliderValue;
let precentAmout = base * (precentage / 365 * 30);
let commisionAmout = base * commision;
let totalCost = commisionAmout + precentAmout;
let totalSum = base + commisionAmout + precentAmout;
console.log(base);
$('#cost').text(totalCost);
$('#sum').text(totalSum);
}
$('#slider').on('change', function () {
$('#amout').text(this.value);
cost(this.value);
});})
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div class="calc">
<div class="range-title">
<h2 class="range-label">Ile chcesz pożyczyć?</h2>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<div class="display-wrap">
<span id="amout">500</span><span class="currency"> zł</span>
</div>
</div>
<div class="range-wrap">
<button class="buttons-change-value">-</button>
<input id="slider" class="range-input" type="range" min="500" max="1500" step="50" value="500">
<button class="buttons-change-value">+</button>
</div>
<div class="summary-container">
<div class="summary-box">
<h3>Koszt:<br>
<span id="cost">200</span><span class="currency"> zł</span></h3>
</div>
<div class="summary-box">
<h3>Do zwrotu:<br>
<span id="sum">200</span><span class="currency"> zł</span></h3>
</div>
<div class="summary-box">
<h3>RRSO:<br>
<span id="rrso">200</span><span class="percentage"> %</span></h3>
</div>
</div>
</div>
</body>
</html>
Related
I have the following 2 buttons.
<div class = "slider-container" style="">
<div id = "x-slider" style="">
X Axis<input id="XSlider" type="range" min="1.0" max="100.0" value="1.0" onChange="update()" />
</div>
<div id = "y-slider" style="">
Y Axis<input id="YSlider" type="range" min="1.0" max="100.0" value="1.0" onChange="update()" />
</div>
</div>
Here is the update() function.
function update(){
let x = document.getElementById("Xslider").value
let y = document.getElementById("Yslider").value
adjust(x, y)
}
The update() calls adjust() only when the mouse button has finished dragging. How can I have the update() function call adjust() in real-time while I'm dragging the slider and not just when I'm finished dragging?
Try this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div class = "slider-container" style="">
<div id = "x-slider" style="">
X Axis: <span id="x"></span><input id="XSlider" type="range" min="1.0" max="100.0" value="1.0" oninput="update()">
</div>
<div id = "y-slider" style="">
Y Axis : <span id="y"></span><input id="YSlider" type="range" min="1.0" max="100.0" value="1.0" oninput="update()">
</div>
</div>
<script>
function update(){
let x = document.getElementById("XSlider").value;
let y = document.getElementById("YSlider").value;
document.getElementById("x").innerText = x;
document.getElementById("y").innerText = y;
}
</script>
</body>
</html>
Edit: Please note that the onInput event is not supported in IE
I think what you want to do is change onchange to oninput.
This should do it, test to see console value
var x = document.getElementById('XSlider')
var y = document.getElementById('YSlider')
function update( e ){
console.log( e.target.value )
}
x.addEventListener('input', update );
y.addEventListener('input', update );
<div class="slider-container" style="">
<div id="x-slider" style="">
X Axis<input id="XSlider" type="range" min="1.0" max="100.0" value="1.0" onChange="update">
</div>
<div id="y-slider" style="">
Y Axis<input id="YSlider" type="range" min="1.0" max="100.0" value="1.0">
</div>
</div>
I am trying to add and remove the price when the check box is checked and unchecked. I am using an event listener function but it is not working how I want it to. How will I be able to click on either of the check boxes to add to the total and remove when unchecked?
HTML:
window.addEventListener('load', function() {
'use strict';
const form = document.getElementById('orderForm');
form.addEventListener("change", function() {
var total = 0;
const checkboxes = form.querySelectorAll('input[data-price][type=checkbox]');
const checkboxCount = checkboxes.length;
for (let i = 0; i < checkboxCount; i++) {
const checkbox = checkboxes[i];
if (checkbox.checked) {
total += parseFloat(checkbox.dataset.price);
form.total.value = total;
var boxTotal = parseFloat(total);
boxTotal = boxTotal.toFixed(2);
form.total.value = boxTotal;
} else {
form.total.value -= this.value;
}
}
});
});
<form id="orderForm">
<section id="selectRecords">
<div class="item">
<span class="price">10.80</span>
<span class="chosen"><input type="checkbox" data-price="9.80"></span>
</div>
<div class="item">
<span class="price">15.70</span>
<span class="chosen"><input type="checkbox" data-price="12.70"></span>
</div>
<div class="item">
<span class="price">18.20</span>
<span class="chosen"><input type="checkbox" data-price="8.20"></span>
</div>
</section>
<section id="checkCost">
Total <input type="text" name="total" size="10" readonly="">
</section>
</section>
</form>
Because you're summing up all checkboxes associated prices on change, you shouldn't have the } else { form.total.value -= this.value; - not only does this refer to the form (which doesn't have a .value), you also don't care at all about the unchecked prices, because they don't affect final value after a change event anyway.
You can select only the checked checkboxes in your query string with the :checked psuedo-selector - this will let you leave out the if (checkbox.checked) part.
You also might consider coming up with the total number once, and then assigning to the input's value once, rather than on every iteration:
const form = document.getElementById('orderForm');
form.addEventListener("change", function() {
let total = 0;
const checkboxes = form.querySelectorAll('input[data-price][type=checkbox]:checked');
const checkboxCount = checkboxes.length;
for (let i = 0; i < checkboxCount; i++) {
const checkbox = checkboxes[i];
total += Number(checkbox.dataset.price);
}
form.total.value = total.toFixed(2);
});
<form id="orderForm">
<section id="selectRecords">
<div class="item">
<span class="price">10.80</span>
<span class="chosen"><input type="checkbox" name="record[]" value="973" data-price="9.80"></span>
</div>
<div class="item">
<span class="price">15.70</span>
<span class="chosen"><input type="checkbox" name="record[]" value="974" data-price="12.70"></span>
</div>
<div class="item">
<span class="price">18.20</span>
<span class="chosen"><input type="checkbox" name="record[]" value="975" data-price="8.20"></span>
</div>
</section>
<section id="checkCost">
Total <input type="text" name="total" size="10" readonly="">
</section>
</section>
</form>
Also, to be a bit more functional, you might use Array.prototype.reduce to calculate the total, rather than a for loop:
const form = document.getElementById('orderForm');
form.addEventListener("change", function() {
const total = Array.prototype.reduce.call(
form.querySelectorAll('input[data-price][type=checkbox]:checked'),
(a, checkbox) => a + Number(checkbox.dataset.price),
0
);
form.total.value = total.toFixed(2);
});
<form id="orderForm">
<section id="selectRecords">
<div class="item">
<span class="price">10.80</span>
<span class="chosen"><input type="checkbox" name="record[]" value="973" data-price="9.80"></span>
</div>
<div class="item">
<span class="price">15.70</span>
<span class="chosen"><input type="checkbox" name="record[]" value="974" data-price="12.70"></span>
</div>
<div class="item">
<span class="price">18.20</span>
<span class="chosen"><input type="checkbox" name="record[]" value="975" data-price="8.20"></span>
</div>
</section>
<section id="checkCost">
Total <input type="text" name="total" size="10" readonly="">
</section>
</section>
</form>
I have following code:
<div>
<div id="1">
<h3>Price: 50</h3>
<span id="price" min-price="50"></span>
</div>
<div id="2">
<h3>Price: 30</h3>
<span id="price" min-price="30"></span>
</div>
<div id="3">
<h3>Price: 40</h3>
<span id="price" min-price="40"></span>
</div>
</div>
I need to sort these 3 divs based on min-price attribute. Is it possible in Jquery? I found sort() function, but I was not able to use it correctly. Thank you.
Try this :
$(document).ready(function() {
$("div[id]").each(function(number,ele) {
$("div[id]").not($(ele)).each(function(index,el){
a = $(ele).find("span").attr("min-price");
b = $(el).find("span").attr("min-price");
if( parseFloat(a) > parseFloat(b) )
$(ele).insertAfter($(el));
})
})
})
<div>
<div id="1">
<h3>Price: 50</h3>
<span id="price" min-price="50"></span>
</div>
<div id="2">
<h3>Price: 30</h3>
<span id="price" min-price="30"></span>
</div>
<div id="3">
<h3>Price: 40</h3>
<span id="price" min-price="40"></span>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
You can use .sort() function:
$('div[id]').sort(function (a, b) {
var minprice1 = parseInt( $(a).find('span').attr('min-price'));
var minprice2 = parseInt( $(b).find('span').attr('min-price'));
return (minprice1 < minprice2 ) ? -1 : (minprice1 > minprice2 ) ? 1 : 0;
});
function sortElements(element, prop, sortDescending) {
var arrElements = [], origElements = [];
$.each(element, function(){
arrElements.push($(this).attr(prop));
origElements.push($(this).attr(prop));
});
arrElements.sort();
if(sortDescending)
arrElements.reverse();
for(var i = 0, l = arrElements.length; i < l; i++)
$("#sortDiv").append($("#"+arrElements[i]));
$("#divOrig").html($("#sortDiv").html());
$("#sortDiv").remove();
}
sortElements($("#divOrig span"), "min-price", true);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="divOrig">
<div id="50">
<h3>Price: 50</h3>
<span id="price" min-price="50"></span>
</div>
<div id="30">
<h3>Price: 30</h3>
<span id="price" min-price="30"></span>
</div>
<div id="40">
<h3>Price: 40</h3>
<span id="price" min-price="40"></span>
</div>
</div>
<div id="sortDiv" style="display:none" ></div>
I've read a lot about uncaught reference errors here and think I have the idea down - when the script is trying to call a function or reference a variable that hasn't been initialized yet. However, I am uncertain how to fix this, and why in my case one function works and the other doesn't.
I have one JS file with two functions in it, and one HTML file with a form. The form calls function1 onSubmit, and that works fine. A radio button inside of the form calls function2 onClick, and that's when I get the error:
Uncaught ReferenceError: toggleGender is not defined onclick # forms.html:20
Why would my first function work and not the second? It seems to me like they are operating under the same premise.
function calculatePFT()
{
var userForm = document.getElementById('userValues');
var pullups = userForm.userPullups.value;
var crunches = userForm.userCrunches.value;
var runMinutes = userForm.userMinutes.value;
var runSeconds = userForm.userSeconds.value;
var runScore = 0;
if(runMinutes < 18) { runScore = 100; }
else
{
var minDiff = runMinutes - 18;
var minPoints = minDiff * 6;
var secPoints = Math.ceil(runSeconds/10);
runScore = 100 - (minPoints + secPoints);
}
var score = parseInt(pullups*5) + parseInt(crunches) + parseInt(runScore);
document.getElementById('scoreBox').innerHTML = "You scored " + pullups + " pullups and " + crunches + " crunches and a run time of " + runMinutes + " minutes " + runSeconds + " seconds. TOTAL SCORE: " + score;
}
function toggleGender(var gender)
{
alert("Inside");
var maleForm = document.getElementById('male');
var femaleForm = document.getElementById('female');
if(gender == "f")
{
alert("Female");
maleForm.style.display = 'none';
femaleForm.style.display = 'block';
}
else
{
alert("Male");
maleForm.style.display = 'block';
femaleForm.style.display = 'none';
}
}
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>Javascript Testing</title>
<link rel="stylesheet" href="style.css" />
<script src="scripts.js"></script>
</head>
<body>
<section id="wrapper">
<h3>PFT Calculator</h3>
<form action="#" id="userValues" method="post" onSubmit="calculatePFT()">
<div id="gender">
<span class="maleFemale">Male <input type="radio" name="maleFemale" value="male" CHECKED onClick="toggleGender('m')" /></span>
<span class="maleFemale">Female <input type="radio" name="maleFemale" value="female" onClick="toggleGender('f')" /></span>
</div>
<div id="male">
<div class="scoreLine">
<div class="label">Pullups:</div>
<div class="entry"><input type="number" name="userPullups" min="0" max="20" default="18" class="scoreEntry" required /></div>
</div>
</div>
<div id="female">
<div class="scoreLine">
<div class="label">Hang:</div>
<div class="entry"><input type="number" name="userHang" min="0" max="150" default="70" class="scoreEntry" required /></div>
</div>
</div>
<div class="scoreLine">
<div class="label">Crunches:</div>
<div class="entry"><input type="number" name ="userCrunches" min="0" max="100" default="100" class="scoreEntry" required /></div>
</div>
<div class="scoreLine">
<div class="label">Run (Minutes):</div>
<div class="entry"><input type="number" name="userMinutes" min="0" max="100" default="19" class="scoreEntry" required /></div>
</div>
<div class="scoreLine">
<div class="label">Run (Seconds):</div>
<div class="entry"><input type="number" name="userSeconds" min="0" max="59" default="30" class="scoreEntry" required /></div>
</div>
<div style="text-align:center;"><input type="submit" value="Calculate Score!" id="submitButton" /></div>
</form>
<span id="scoreBox"></span>
</section>
</body>
</html>
function toggleGender(var gender)
You have a syntax error here. Argument names should not be prefixed by var. This causes the functional declaration to fail (hence why you get a reference error when you try to call it).
function calculatePFT()
{
var userForm = document.getElementById('userValues');
var pullups = userForm.userPullups.value;
var crunches = userForm.userCrunches.value;
var runMinutes = userForm.userMinutes.value;
var runSeconds = userForm.userSeconds.value;
var runScore = 0;
if(runMinutes < 18) { runScore = 100; }
else
{
var minDiff = runMinutes - 18;
var minPoints = minDiff * 6;
var secPoints = Math.ceil(runSeconds/10);
runScore = 100 - (minPoints + secPoints);
}
var score = parseInt(pullups*5) + parseInt(crunches) + parseInt(runScore);
document.getElementById('scoreBox').innerHTML = "You scored " + pullups + " pullups and " + crunches + " crunches and a run time of " + runMinutes + " minutes " + runSeconds + " seconds. TOTAL SCORE: " + score;
}
function toggleGender(gender)
{
alert("Inside");
var maleForm = document.getElementById('male');
var femaleForm = document.getElementById('female');
if(gender == "f")
{
alert("Female");
maleForm.style.display = 'none';
femaleForm.style.display = 'block';
}
else
{
alert("Male");
maleForm.style.display = 'block';
femaleForm.style.display = 'none';
}
}
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>Javascript Testing</title>
<link rel="stylesheet" href="style.css" />
<script src="scripts.js"></script>
</head>
<body>
<section id="wrapper">
<h3>PFT Calculator</h3>
<form action="#" id="userValues" method="post" onSubmit="calculatePFT()">
<div id="gender">
<span class="maleFemale">Male <input type="radio" name="maleFemale" value="male" CHECKED onClick="toggleGender('m')" /></span>
<span class="maleFemale">Female <input type="radio" name="maleFemale" value="female" onClick="toggleGender('f')" /></span>
</div>
<div id="male">
<div class="scoreLine">
<div class="label">Pullups:</div>
<div class="entry"><input type="number" name="userPullups" min="0" max="20" default="18" class="scoreEntry" required /></div>
</div>
</div>
<div id="female">
<div class="scoreLine">
<div class="label">Hang:</div>
<div class="entry"><input type="number" name="userHang" min="0" max="150" default="70" class="scoreEntry" required /></div>
</div>
</div>
<div class="scoreLine">
<div class="label">Crunches:</div>
<div class="entry"><input type="number" name ="userCrunches" min="0" max="100" default="100" class="scoreEntry" required /></div>
</div>
<div class="scoreLine">
<div class="label">Run (Minutes):</div>
<div class="entry"><input type="number" name="userMinutes" min="0" max="100" default="19" class="scoreEntry" required /></div>
</div>
<div class="scoreLine">
<div class="label">Run (Seconds):</div>
<div class="entry"><input type="number" name="userSeconds" min="0" max="59" default="30" class="scoreEntry" required /></div>
</div>
<div style="text-align:center;"><input type="submit" value="Calculate Score!" id="submitButton" /></div>
</form>
<span id="scoreBox"></span>
</section>
</body>
</html>
I am trying to build a simple Pension calculator. Three inputs are taken in one form page and the result is displayed in another page. Output is in text format. But the following problem happens:
The output is shown as e.g. 2100021000 instead of actual 21000 this happens in all calculated results.
How to display results properly without the repeats ?
How do I display results in three separate text boxes in the results page similar to the text input form page ? I'm new to this. Need help.
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta content='width=device-width, initial-scale=1' name='viewport'/>
<title>Pension Calculator</title>
<link rel="stylesheet" href="js1/jquery.mobile-1.4.3.min.css" type="text/css"/>
<script src="js1/jquery-1.11.1.min.js" type="text/javascript"></script>
<script src="js1/jquery.mobile-1.4.3.min.js" type="text/javascript"></script>
<script>
// Bind to 'pageinit' event for our data page
//$(document).delegate('#data', 'pageinit', function(){
$(document).on('pagecreate', '#page1', function() {
// Do some processing when the button with id 'calc' is clicked or tapped
$('#calc').bind('click', function() {
//event.preventDefault();
var basic = $('[name="basic"]').val(),
pbasic = $('[name="pbasic"]').val(),
gratuity = $('[name="gratuity"]').val(),
da = $('[name="da"]').val(),
years = $('[name="years"]').val(),
total = $('[name="total"]').val(),
basic = basic + (basic*da/100);
pbasic = basic/2;
da = pbasic*da/100;
gratuity = (basic) + ((da))*15/26 * years;
if
(gratuity > 1000000)
gratuity = 10000000;
total = (pbasic) + (da);
gratuity = gratuity.toFixed(2);
pbasic = pbasic.toFixed(2);
total = total.toFixed(2);
// Get to the DOM node that has the actual BMI text
// while ($total.children().length) {
// $total = $total.children().first();
// Set it to the calculated value
// $total.text(total);
$result = $('#results #gratuity');
$result.text(gratuity);
$result = $('#results #pbasic');
$result.text(pbasic);
$result = $('#results #total');
$result.text(total);
});
});
</script>
</head>
<body>
<div id="page1" data-role="page">
<header data-role="header">
<h1>Simple Pension Calculator</h1>
</header>
<div data-role="content" data-theme="a">
<div data-role="content">
<form id="theForm">
<div data-role="fieldcontain" data-inset="true">
<label for="basic">Present Basic (Basic including Grade Pay + NPA)</label>
<input type="number" name="basic" id="basic" value="0" autofocus required>
</div>
<div data-role="fieldcontain">
<label for="years">Years of Service</label>
<input type="number" name="years" id="years" value="0" required>
</div>
<div data-role="fieldcontain">
<label for="da">Existing DA (%)</label>
<input type="number" name="da" id="da" value="0" required>
</div>
</form>
<a id="calc" href="#results" data-role="button" data-icon="gear">Calculate</a>
</div>
</div>
</div>
<div id="results" data-url="results" data-role="page">
<div data-role="header">
<h1>Results</h1>
</div>
<div data-role="content">
Your Gratuity:<br>
<span id="gratuity"><span style="font-size: 52px; "><strong>24</strong></span></span><br>
Your Basic Pension:<br>
<span id="pbasic"><span style="font-size: 52px; "><strong>24</strong></span></span><br>
Your Pension:<br><br>
<span id="total"><span style="font-size: 52px; "><strong>24</strong></span></span>
</div>
</div>
</body>
</html>
Clean up your code like this:
<div id="page1" data-role="page">
<header data-role="header">
<h1>Simple Pension Calculator</h1>
</header>
<div role="main" class="ui-content">
<form id="theForm">
<div data-role="fieldcontain" data-inset="true">
<label for="basic">Present Basic (Basic including Grade Pay + NPA)</label>
<input type="number" name="basic" id="basic" value="0" autofocus required />
</div>
<div data-role="fieldcontain">
<label for="years">Years of Service</label>
<input type="number" name="years" id="years" value="0" required />
</div>
<div data-role="fieldcontain">
<label for="da">Existing DA (%)</label>
<input type="number" name="da" id="da" value="0" required />
</div>
</form>
<a id="calc" href="#results" data-role="button" data-icon="gear">Calculate</a>
</div>
</div>
<div id="results" data-url="results" data-role="page">
<div data-role="header">
<h1>Results</h1>
</div>
<div role="main" class="ui-content">
Your Gratuity:<br />
<span id="gratuity" class="resultspan"></span><br />
Your Basic Pension:<br />
<span id="pbasic" class="resultspan"></span><br />
Your Pension:<br />
<span id="total" class="resultspan"></span>
</div>
</div>
Style the results span with CSS class instead of inline:
.resultspan {
font-size: 52px;
font-weight: bold;
}
In the script, pbasic, gratuity and total are not read from the DOM but rather set during calculation, so initialize them to zero. When reading other values from the inputs, you can use parseInt() to ensure the text is converted to integers before using them in the calculations:
$('#calc').on('click', function() {
//event.preventDefault();
var basic = parseInt($('#basic').val()),
da = parseInt($('#da').val()),
years = parseInt($('#years').val()),
pbasic = 0,
gratuity = 0,
total = 0;
basic = basic + (basic*da/100);
pbasic = basic/2;
da = pbasic*da/100;
gratuity = (basic) + ((da))*15/26 * years;
if (gratuity > 1000000)
gratuity = 10000000;
total = (pbasic) + (da);
gratuity = gratuity.toFixed(2);
pbasic = pbasic.toFixed(2);
total = total.toFixed(2);
$('#results #gratuity').text(gratuity);
$('#results #pbasic').text(pbasic);
$('#results #total').text(total);
});
Working DEMO