how can i fix my javascript calculation which is not working? - javascript

the problem is the "total price" is not working.when i pick the "pickup date" and "drop date" it will show the value in the input form. i have to key in the number in "number of days" then the total price will calculate. i need the "total of price" is auto calculate. i have try various event of javascript. here i will attach my code. hope someone will help me. thanks in advance.
function sum() {
var txtFirstNumberValue = document.getElementById('num1').value;
var txtSecondNumberValue = document.getElementById('numdays2').value;
var result = parseInt(txtFirstNumberValue) * parseInt(txtSecondNumberValue);
if (!isNaN(result)) {
document.getElementById('num3').value = result;
}
}
function GetDays() {
var dropdt = new Date(document.getElementById("drop_date").value);
var pickdt = new Date(document.getElementById("pick_date").value);
return parseInt((dropdt - pickdt) / (24 * 3600 * 1000));
}
function cal() {
if (document.getElementById("drop_date")) {
document.getElementById("numdays2").value = GetDays();
}
}
<label for="total">Price per day:</label>
<input type="text" name="price" id="num1" onkeyup="sum();" value="3" readonly>
<div id="pickup_date">
<p><label class="form">Pickup Date:</label>
<input type="date" class="textbox" id="pick_date" name="pickup_date" onchange="cal()" /></p>
</div>
<div id="dropoff_date">
<p><label class="form">Dropoff Date:</label>
<input type="date" class="textbox" id="drop_date" name="dropoff_date" onchange="cal()" /></p>
</div>
<div id="reserve_form">
<div id="numdays"><label class="form">Number of days:</label>
<input type="text" id="numdays2" name="numdays" oninput="sum();" />
<label for="total">Total Price (RM)</label>
<input type="text" name="test" placeholder="Total Price" value="" id="num3">
i expect that the total price can automatically calculate.

You just need to make sure your sum function (or in the example just cal) is being called when your inputs are complete and valid. Since you may want to restrict the user from manually setting the number of days I've demonstrated how you might do this by firing a change event programmatically. It's also current practice to attach events to elements programmatically instead of using the inline HTML5 event notation (e.g. "onchange=foo"), see Why are inline event handler attributes a bad idea in modern semantic HTML?
function setDate(event) {
var days = getDays();
// if the number of days is valid
if (!isNaN(days)) {
var nod = document.getElementById("numdays2");
nod.value = days;
// programmatically setting a value will not fire a change event
nod.dispatchEvent(new Event("change"));
}
}
function getDays() {
// returns NaN if either date does not hold a valid date
var dropdt = new Date(document.getElementById("drop_date").value);
var pickdt = new Date(document.getElementById("pick_date").value);
return parseInt((dropdt - pickdt) / (24 * 3600 * 1000));
}
function cal() {
var pricePerDay = document.getElementById("pricePerDay").value;
if (0 == (pricePerDay = parseInt(pricePerDay))) { return } // TODO needs to handle decimal values
document.getElementById("total").value = parseInt(document.getElementById("numdays2").value) * pricePerDay;
}
function init() {
document.getElementById("drop_date").addEventListener("change", setDate);
document.getElementById("pick_date").addEventListener("change", setDate);
document.getElementById("numdays2").addEventListener("change", cal);
}
document.addEventListener("DOMContentLoaded", init);
<label for="total">Price per day:</label>
<input type="text" name="price" id="pricePerDay" value="" placeholder="Manually enter a value">
<div id="pickup_date">
<p><label class="form">Pickup Date:</label>
<input type="date" class="textbox" id="pick_date" name="pickup_date" /></p>
</div>
<div id="dropoff_date">
<p><label class="form">Dropoff Date:</label>
<input type="date" class="textbox" id="drop_date" name="dropoff_date" /></p>
</div>
<div id="reserve_form">
<div id="numdays"><label class="form">Number of days:</label>
<!-- numdays2 is readonly to ensure the date pickers are used -->
<input type="text" id="numdays2" name="numdays" readonly placeholder="Select dates above" />
<label for="total">Total Price (RM)</label>
<input id="total" type="text" readonly name="test" placeholder="Total Price" value="" id="num3">
</div>
</div>

Related

javascript multiply 2 number show total and gtotal but show only one value?

I am using javascript calculation. multiply 2 numbers: number 1 * number 2 = total and how g-total but working only one value display?
I have need number 1 * number 2 = total and show Gtotal so please help and share a valuable idea...
HTML
<input
name="per_hour"
id="per_hour"
class="form-control"
value=""
onblur="perhour()"
placeholder="0"
/>
<input
name="per_hour_x"
id="per_hour_x"
class="form-control"
onblur="perhour()"
value=""
placeholder="0.00"
/>
Total
<input
name="per_hour_total"
id="per_hour_total"
class="form-control"
value=""
placeholder="0.00"
/>
G-Total
<input
type="text"
class="form-control total-fare"
id="total"
disabled
value="<?= $booking->total_fare ?>"
/>
<script>
function perhour() {
var per_hour = document.getElementById("per_hour").value;
var per_hour_x = document.getElementById("per_hour_x").value;
var amts = document.getElementById("total").value;
var totaperhour = Number(per_hour) * Number(per_hour_x);
var totalamt = Number(totaperhour) + Number(amts);
$("#per_hour_total").val(totaperhour).toFixed(2); //working
$("#total").val(totalamt).toFixed(2); //not working
}
</script>
It should be $('#per_hour_total').val(totaperhour.toFixed(2)); and not $('#per_hour_total').val(totaperhour).toFixed(2);
function perhour() {
var per_hour = document.getElementById("per_hour").value;
var per_hour_x = document.getElementById("per_hour_x").value;
var amts = document.getElementById("total").value;
var totaperhour = Number(per_hour) * Number(per_hour_x);
var totalamt = Number(totaperhour) + Number(amts);
$('#per_hour_total').val(totaperhour.toFixed(2));
$('#total').val(totalamt.toFixed(2));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<div>
total
<input type="text" class="form-control total-fare" disabled id="total" value="">
</div>
<div>
per_hour
<input name="per_hour" id="per_hour" class="form-control" value="" onblur="perhour()" placeholder="0">
</div>
<div>
per_hour_x
<input name="per_hour_x" id="per_hour_x" class="form-control" onblur="perhour()" value="" placeholder="0.00">
</div>
<div>
per_hour_total
<input name="per_hour_total" id="per_hour_total" class="form-control" value="" placeholder="0.00">
</div>

show result which is created through JavaScript in input field

I have a form in which a date/time picker is working fine.
I created JavaScript to calculate the two fields' date difference and show in a third field - named Course Duration.
Somehow I am not able to display the results in the "Course Duration" input Field.
Code:
function GetDays() {
var dropdt = new Date(document.getElementById("course_end_date").value);
var pickdt = new Date(document.getElementById("admission_date").value);
return parseInt((dropdt - pickdt) / (24 * 3600 * 1000));
}
function cal() {
if (document.getElementById("course_end_date")) {
document.getElementById("course_duration").value = GetDays();
}
}
<input id="admission_date" name="admission_date" placeholder="" type="text" class="form-control" value="" />
<input id="course_end_date" name="course_end_date" placeholder="" type="text" class="form-control" value="" />
<input id="course_duration" name="course_duration" placeholder="" type="text" class="form-control" value="" />
You need something to trigger the cal() function, which currently you don't have.
So I made a demo below which has a "Calculate" button. Enter your dates and then press the button, and it will run the calculation. As long as you enter valid dates, it should work.
For example, if you enter 2018-02-01 and 2018-02-02 it will return 366.
var calcButton = document.getElementById("calculate");
calcButton.addEventListener("click", cal);
function GetDays() {
var dropdt = new Date(document.getElementById("course_end_date").value);
var pickdt = new Date(document.getElementById("admission_date").value);
return parseInt((dropdt - pickdt) / (24 * 3600 * 1000));
}
function cal() {
if (document.getElementById("course_end_date")) {
document.getElementById("course_duration").value = GetDays();
}
}
<input id="admission_date" name="admission_date" placeholder="" type="text" class="form-control" value="" />
<input id="course_end_date" name="course_end_date" placeholder="" type="text" class="form-control" value="" />
<button id="calculate" type="button">Calculate</button>
<input id="course_duration" name="course_duration" placeholder="" type="text" class="form-control" value="" />

Javascript: Update price when quantity changes

I am new to javascript and I have been working on this for 4 days now and I haven't made any progress. I have tried a bunch of different options. I saw an example like mine that worked...but it isn't working for me. :( I am trying to have the price adjust as the quantity of tickets changes. Below is the javascript and below that is the html. Any assistance is much appreciated! Thank you!
document.getElementById("totalTicketCost").value = 0 + "." + 00;
function ticketCost()
{
var ticketCost = 5.5;
var inputTicketQuantity = document.getElementById("inputTicketQuantity").value;
var totalTicketCost = parseFloat(ticketCost) * inputTicketQuantity;
if (!isNaN(totalTicketCost))
document.getElementById("totalTicketCost").innerHTML = totalTicketCost;
}
<form onsubmit="" ="return alertDetails()" id="formPurchaseTickets" enctype="text/plain" method="post" action="mailto:cmst388#xyz.com">
<h1>Ticket Purchasing Form</h1>
<p class="alert">Act fast! This transaction must be completed in <span id="timer"></span> minutes.</p>
<div class="field">
<label class="required">How many tickets would you like to purchase?</label>
<input id="inputTicketQuantity" tabindex="1" required type="number" value="0" name="ticket-quantity" min="1" max="3" step="1" title="You can only buy between 1 and 3 tickets">
$<span id="totalTicketCost">0.00</span>
</div>
<div id="contactInfo" style="display:none;">
<div class="field">
<label class="required">Name:</label>
<input required name="name" tabindex="2" type="text" placeholder="Enter name" pattern="[a-zA-Z\s]+" title="Enter only letters. e.g. Smith">
</div>
<div class="field">
<label class="required">E-mail:</label>
<input id="inputEmail" tabindex="3" required name="email" type="email" placeholder="Enter e-mail address" onblur="validateEmail()">
</div>
</div>
<hr>
<input type="submit" tabindex="4" value="Purchase Tickets"> <input type="reset">
</form>
<script src="event_registration.js"></script>
</body>
Going with only ES5 here (assuming you're not transpiling at this stage), I did a quick refactor.
var ticketInput = document.getElementById("totalTicketCost");
var inputTicketQuantity = document.getElementById("inputTicketQuantity");
var ticketCost = 5.5;
// Handle the precision up to >= $100
function changeCost( num ) {
var cost = new Number( parseFloat( num ) * ticketCost );
var precision = cost.toString().length === 3 ? 3 : 4;
return cost.toPrecision( precision );
}
inputTicketQuantity.addEventListener('input', function( event ) {
var value = event.target.value;
if ( !isNaN( value ) ) {
ticketInput.innerHTML = changeCost( value );
}
});
You definitely want to separate out the JS from the HTML as much as possible, avoid the hard to read inline stuff like <form onsubmit="" ="return alertDetails()", should at least be <form onsubmit="return alertDetails()" to fix it.
Add an event listener to you quantity field, and recalculate price.
document.querySelector("#inputTicketQuantity").addEventListener("input", function() {
let count = this.value;
calculatePrice(count);
});
Your question is not very specific on what you're trying to achieve, but here is functionality to update your total cost as the user adds tickets -
In JS:
function updateCost(count)
{
var ticketCost = 5.5;
document.getElementById("totalTicketCost").innerHTML = count * ticketCost;
}
In HTML
<input id="inputTicketQuantity" tabindex="1" required type="number" value="0" name="ticket-quantity" onchange="updateCost(this.value)" min="1" max="3" step="1" title="You can only buy between 1 and 3 tickets">
You have to call function ticketCost() on value change event of input quantity textbox
<input id="inputTicketQuantity" onkeydown="ticketCost()" tabindex="1" required type="number" value="0" name="ticket-quantity" min="1" max="3" step="1" title="You can only buy between 1 and 3 tickets">
Or you can add listener in JavaScript as
document.getElementById("inputTicketQuantity").addEventListener("onkeydown", ticketCost);
Add it outside your JavaScript function ticketCost()

How to display recommendations after calculating a certain result?

How do I display something like a recommendation list after a user calculate a result from the inputs? E.g having the user to key in the salaries of the family and calculating the PCI (Per capita income) and after they key in and press on the calculate button which then will trigger a list of recommendations based on the amount of PCI the family have (Maybe tables that shows different results based on different categories of PCI?)
<!DOCTYPE html>
<html>
<head>
<script src="common.js"></script>
<script>
function cal()
{
var salary1 = document.getElementById('salary1').value;
var salary2 = document.getElementById('salary2').value;
var salary3 = document.getElementById('salary3').value;
var salary4 = document.getElementById('salary4').value;
var members = document.getElementById('members').value;
var total = (parseInt(salary1) + parseInt(salary2) + parseInt(salary3) + parseInt(salary4)) / parseInt(members);
document.getElementById('total').value = total;
alert (total);
}
</script>
</head>
<body>
<h1>Want to know which bursary your eligible?</h1>
<input id="salary1" value="" placeholder="Enter your 1st family income..."/>
<input id="salary2" value="" placeholder="Enter your 2nd family income..."/>
<input id="salary3" value="" placeholder="Enter your 3rd family income..."/>
<input id="salary4" value="" placeholder="Enter your 4th family income..."/>
<input id="members" value="" placeholder="Enter the total number of family members..."/>
<br>
<button onclick="cal()"> Calculate PCI!</button>
<br>
Total: <input id="total"> </input>
</body>
</html>
You can create a hidden div that holds the data then show that div when user clicks the button
HTML:
<div id="divToShow" style="display:none;" class="table_list" >
//put your data table here
</div>
<input type="button" name="myButton" value="Show Div" onclick="showDiv()" />
Javascript:
function showDiv() {
document.getElementById('divToShow').style.display = "block";
}
This should get you there: Jsfiddle.
<form id="form">
<input id="number1" type="number" min="1" name="number" placholder="add value one"> +
<input id="number2" type="number" min="1" name="number" placholder="add value one">
<button>Submit</button>
</form>
var form = document.getElementById('form');
number1 = document.getElementById('number1');
number2 = document.getElementById('number2');
form.onsubmit = function() {
var total = +number1.value + +number2.value; // add + before
alert( total );
};
function cal(){
var salary1 = document.getElementById('salary1').value;
var salary2 = document.getElementById('salary2').value;
var salary3 = document.getElementById('salary3').value;
var salary4 = document.getElementById('salary4').value;
var members = document.getElementById('members').value;
var recommanted;
var recommandations=[
{maxpci:1000,recommandation:'first_recommandation'},
{maxpci:2000,recommandation:'second_recommandation'},
{maxpci:3000,recommandation:'third_recommandation'},
{maxpci:6000,recommandation:'fourth_recommandation'}
];
var total=(parseInt(salary1) + parseInt(salary2) + parseInt(salary3) + parseInt(salary4)) / parseInt(members);
if(recommandations[recommandations.length - 1].maxpci < total ){recommanted=recommandations[recommandations.length - 1].recommandation;}
else{
for (var i = 0; i < recommandations.length; i++) {
if(total <= recommandations[i].maxpci){
recommanted=recommandations[i].recommandation;break;}
}}
document.getElementById('result').innerHTML = "Your PCI : "+total+"</br>Recommandation : "+recommanted;
}
<h1>Want to know which bursary your eligible?</h1>
<input id="salary1" type="number" value="" placeholder="Enter your 1st family income..."/>
<input id="salary2" type="number" value="" placeholder="Enter your 2nd family income..."/>
<input id="salary3" type="number" value="" placeholder="Enter your 3rd family income..."/>
<input id="salary4" type="number" value="" placeholder="Enter your 4th family income..."/>
<input id="members" type="number" value="" placeholder="Enter the total number of family members..."/>
</br>
<button onclick="cal()"> Calculate PCI!</button>
</br>
<div id="result">
</div>

Calculate change to be given to customer on POS javascript

Can any one help me with this, I'm trying to use this code on a POS to calculate the change to give a customer and it works for the must part.
The problem I'm having is if I an order costs £9.99 and I enter £10, instead of it calculating the change as £0.01 it calculates it as £ 0.009999999999999787
Here is the code that I'm using.
function sum() {
var og_total = document.getElementById('og_cart_total').value;
var og_tendered = document.getElementById('og_cash_tendered').value;
var og_change = (og_tendered - og_total).toFixed(2);
var og_symbol = '£';
if (!isNaN(og_change)) {
document.getElementById('og_change_given').value = og_symbol + og_change;
}
}
<input type="hidden" id="og_cart_total" value="19.99" onkeyup="sum();" />
<div class="control-group">
<label class="control-label" for="og_cash_tendered">Tendered:</label>
<div class="controls">
<input class="cm-autocomplete-off" type="text" name="payment_info[og_cash_tendered]" value="" id="og_cash_tendered" onkeyup="sum();" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="og_change_given">Change:</label>
<div class="controls">
<input type="text" name="payment_info[og_change_given]" id="og_change_given" value="£-19.99" readonly="readonly" />
</div>
</div>
there is this way but it's not as promising as it should. the best way is to use a library for long numbers if it worth the trouble.
function sum() {
var og_total = document.getElementById('txt1').value;
var og_tendered = document.getElementById('txt2').value;
var og_change = (og_tendered - og_total).toFixed(2);
var og_symbol = "£";
if (!isNaN(og_change)) {
document.getElementById('og_change_text').value = og_symbol + og_change;
}
}
<input type="text" id="txt1" value="9.99" readonly="readonly" onkeyup="sum();" />
<input type="text" id="txt2" onkeyup="sum();" />
<input type="text" readonly="readonly" id="og_change_text" />

Categories