Calculate change to be given to customer on POS javascript - 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" />

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>

Convert string to a slug from multiply text fields using Javascript in real-time

I want to combine the data entered into these four fields into one slug. The slug should look like the following: firstname-middlename-lastname-suffix. How can this be done? Here is my code so far:
<label for="first_name" />First Name</label>
<input onload="convertToSlug(this.value)" onkeyup="convertToSlug(this.value)" type="text" name="first_name" value="" />
<label for="middle_name" />Middle Name</label>
<input onload="convertToSlug(this.value)" onkeyup="convertToSlug(this.value)" type="text" name="middle_name" value="" />
<label for="last_name" />Last Name</label>
<input onload="convertToSlug(this.value)" onkeyup="convertToSlug(this.value)" type="text" name="last_name" value="" />
<label for="suffix" />Suffix</label>
<input onload="convertToSlug(this.value)" onkeyup="convertToSlug(this.value)" type="text" name="suffix" value="" />
</form>
<script>
/* Encode string to slug */
function convertToSlug( str ) {
//replace all special characters | symbols with a space
str = str.replace(/[`~!##$%^&*()_\-+=\[\]{};:'"\\|\/,.<>?\s]/g, ' ').toLowerCase();
// trim spaces at start and end of string
str = str.replace(/^\s+|\s+$/gm,'');
// replace space with dash/hyphen
str = str.replace(/\s+/g, '-');
document.getElementById('url').value = str;
//return str;
}
</script>
<form>
<input type="text" id="url" name="url" value="" />
</form>
You should use convertToSlug like a common function. And in the function, you get the value of all elements and process it.
You can see the live demo here:
/* Encode string to slug */
function convertToSlug() {
var first_name = document.getElementById('first_name').value;
var middle_name = document.getElementById('middle_name').value;
var last_name = document.getElementById('last_name').value;
var suffix = document.getElementById('suffix').value;
// put all text into a array to join by dash
var strings = [first_name, middle_name, last_name, suffix];
// filter the empty value before join to ignore empty input
var str = strings.filter(e => e.length > 0).join('-');
//replace all special characters | symbols with a space
str = str.replace(/[`~!##$%^&*()_\-+=\[\]{};:'"\\|\/,.<>?\s]/g, ' ').toLowerCase();
// trim spaces at start and end of string
str = str.replace(/^\s+|\s+$/gm, '');
// replace space with dash/hyphen
str = str.replace(/\s+/g, '-');
document.getElementById('url').value = str;
//return str;
}
<form>
<div>
<label for="first_name" />First Name</label>
<input onkeyup="convertToSlug()" type="text" name="first_name" id="first_name" value="" />
</div>
<div>
<label for="middle_name" />Middle Name</label>
<input onkeyup="convertToSlug()" type="text" name="middle_name" id="middle_name" value="" />
</div>
<div>
<label for="last_name" />Last Name</label>
<input onkeyup="convertToSlug()" type="text" name="last_name" id="last_name" value="" />
</div>
<div>
<label for="suffix" />Suffix</label>
<input onkeyup="convertToSlug()" type="text" name="suffix" id="suffix" value="" />
</div>
<div>
<label for="suffix" />Slug/Result</label>
<input type="text" id="url" name="url" value="" />
</div>
</form>
see if you like this technique to achive same thing i have tried simplifying your code with an example below
var root = document.querySelector(".root"),
resultEl = document.querySelector(".result")
root.oninput = function(){
resultEl.innerText = getValues(root)
}
function getValues(el){
var output = ""
el.querySelectorAll(".values").forEach(each=>{
if(each.value != ""){output += each.value + "-"}
})
return output.slice(0,-1)
}
<div class="root">
<input class="values" type="text">
<input class="values" type="text">
<input class="values" type="text">
<input class="values" type="text">
<div class="result"></div>
</div>

Combine two textbox value into other textbox in lowercase with dash

I have two text type inputs. I want to convert them into one textbox(Lowercase with dash) while typing just like below.
<input type="text" name="first">
<input type="text" name="last">
I want combine this two text box into another textbox
Example: Nikhil Patel to nikhil-patel
I am trying to combine below inputs but can't.
function conv(){
var title, author;
title = document.getElementById("title").value;
author = document.getElementById("author").value;
/*converting to LowerCase*/
title = String.toLowerCase(title);
author = String.toLowerCase(author);
var out = title + "-" + author;
document.getElementById("output").value = output;
}
<div class="form-group">
<label>Title :</label>
<input class="form-control" type="text" name="title" id="title" />
</div>
<div class="form-group">
<label>Author :</label>
<input class="form-control" type="text" name="author" id="author" />
</div>
<div class="form-group">
<label>Output :</label>
<input class="form-control" type="text" name="output" id="output"/>
</div>
Output is not printing automatically
Try This if you want like this...
var input = $('[name="first"],[name="last"]'),
input1 = $('[name="first"]'),
input2 = $('[name="last"]'),
input3 = $('[name="final"]');
input.change(function () {
input3.val(input1.val() + ' - ' + input2.val());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text" name="first" id="1" value="">
<input type="text" name="last" id="2" value="">
<input type="text" name="final" id="3" value="" readonly>
<HTML>
<HEAD>
<SCRIPT>
function conv(){
var first, second;
first = document.getElementById("first").value;
second = document.getElementById("second").value;
/*converting to LowerCase*/
first = String.toLowerCase(first);
second = String.toLowerCase(second);
var out = first + "-" + second;
document.getElementById("out").value = out;
}
</SCRIPT>
</HEAD>
<BODY>
<input type="text" name = "first" id="first" onkeyup = 'conv()'/>
<input type="text" name = "second" id ="second" onkeyup = 'conv()'/>
<input type="text" name = "out" id="out"/>
</BODY>
</HTML>
this is just a sample with 3 text boxes where
first two boxes will be for input
and third will auto populate using the javascript
I hope it'll help you. All is did was to add extra id's.

Computing using functions and arrays / Output error: Not a Number

Background: I'm practicing arrays and functions and am having trouble computing the sum of array items. I'm pretty sure there is something wrong with the function I'm writing but I'm not sure what. Using 8 input fields I'm pulling data into a array one item at a time and converted to floating numbers(for now...I'll try to fix that later). I've created a function that will compute the total of this list but it only outputs NaN.
Any suggestions are highly appreciated!
function myfunction() {
list = [];
list[0] = parseFloat(document.getElementById('number1').value);
list[1] = parseFloat(document.getElementById('number2').value);
list[2] = parseFloat(document.getElementById('number3').value);
list[3] = parseFloat(document.getElementById('number4').value);
list[4] = parseFloat(document.getElementById('number5').value);
list[5] = parseFloat(document.getElementById('number6').value);
list[6] = parseFloat(document.getElementById('number7').value);
list[7] = parseFloat(document.getElementById('number8').value);
function total(myvals) {
let total = 0;
for (let i = 0; i <= myvals.length; i++) {
total += myvals[i];
}
return total;
}
document.getElementById('results').innerHTML = total(list);
}
<form>
<input type="text" name="number1" id="number1"><br>
<input type="text" name="number2" id="number2"><br>
<input type="text" name="number3" id="number3"><br>
<input type="text" name="number4" id="number4"><br>
<input type="text" name="number5" id="number5"><br>
<input type="text" name="number6" id="number6"><br>
<input type="text" name="number7" id="number7"><br>
<input type="text" name="number8" id="number8"><br>
<input type="submit" value="Compute Score" onclick="javascript:myfunction()">
</form>
<div id="results"></div>
Here is a simple example using a for loop with querySelectorAll.
Additionally, I cleaned up your code a bit. Run the snippet below:
EDIT: Included some comments to show what's happening.
function myfunction() {
let total = 0;
//get the value for each element being called by querySelectorAll
//add values to total to get a sum
document.querySelectorAll('input').forEach(el => total += +el.value);
//append the new value to the results div
document.querySelector('#results').innerHTML = total;
}
<form>
<input type="text" name="number1" id="number1"><br>
<input type="text" name="number2" id="number2"><br>
<input type="text" name="number3" id="number3"><br>
<input type="text" name="number4" id="number4"><br>
<input type="text" name="number5" id="number5"><br>
<input type="text" name="number6" id="number6"><br>
<input type="text" name="number7" id="number7"><br>
<input type="text" name="number8" id="number8"><br>
</form>
<br/><br/>
<button type="submit" onclick="myfunction()">Compute Score</button>
<br/><br/>
<div id="results"></div>
This is resolved. I was able to fix my source code by removing
"<=" in the for loop and adding "<" in its place. Thanks everyone, I will look over everything else for extra practice!
1 - in HTML forms and their elements use names.
2 - each element of a form can be accessed by name with the form as parent
3 - if several elements have the same name (with the same type of preference) then they form an object collection
PS: I have used here [... myForm.numX] to transform the myForm.numX collection to array, so that it can accept the arry.map () method
this way:
const myForm = document.forms['my-form']
, res = document.getElementById('results')
;
myForm.onsubmit = evt =>
{
evt.preventDefault() // disable submit
let list = [...myForm.numX].map(inp => parseFloat(inp.value))
res.textContent = list.reduce((t,v)=>t+v,0)
// control...
console.clear()
console.log( myForm.numX.length, JSON.stringify(list) )
}
<form name="my-form">
<input type="text" name="numX" placeholder="num 1"><br>
<input type="text" name="numX" placeholder="num 2"><br>
<input type="text" name="numX" placeholder="num 3"><br>
<input type="text" name="numX" placeholder="num 4"><br>
<input type="text" name="numX" placeholder="num 5"><br>
<input type="text" name="numX" placeholder="num 6"><br>
<input type="text" name="numX" placeholder="num 7"><br>
<input type="text" name="numX" placeholder="num 8"><br>
<button type="submit">Compute Score</button>
</form>
<div id="results">..</div>

jQuery/Javascript complex iterate over elements

We have a form and need to iterate over some elements to get the final sum to put in a "total" element.
E.g., here is a working starter script. It doesn't NOT iterate over the other ones. It does NOT consider the elements "item*", below, yet but should. Keep reading.
<script>
$( document ).ready(function() {
$('#taxsptotal').keyup(calcgrand);
$('#shiptotal').keyup(calcgrand);
$('#disctotal').keyup(calcgrand);
function calcgrand() {
var grandtot = parseFloat($('#subtotal').val(), 10)
+ parseFloat($("#taxsptotal").val(), 10)
+ parseFloat($("#shiptotal").val(), 10)
- parseFloat($("#disctotal").val(), 10)
$('#ordertotal').val(grandtot);
}
});
</script>
We are adding more to this. Think of having many items in a cart and each one has the same elements for the following where "i" is a number designating an individual item.
<!-- ordertotal = sum of #subtotal, #taxptotal, #shiptotal and #disctotal -->
<input type="text" id="ordertotal" name="ordertotal" value="106.49">
<input type="text" id="taxsptotal" name="taxsptotal" value="6.72">
<input type="text" id="shiptotal" name="shiptotal" value="15.83">
<input type="text" id="disctotal" name="disctotal" value="0.00">
<!-- sum of the cart "itemtotal[i]" -->
<input type="text" id="subtotal" name="subtotal" value="83.94">
<!-- cart items
User can change any itemprice[i] and/or itemquantity[i]
itemtotal[i] = sum(itemquantity[i] * itemprice[i])
-->
<input type="text" name="itemtotal[1]" value="8.97" />
<input type="text" name="itemquantity[1]" value="3" />
<input type="text" name="itemprice[1]" value="2.99" />
<input type="text" name="itemtotal[2]" value="4.59" />
<input type="text" name="itemquantity[2]" value="1" />
<input type="text" name="itemprice[2]" value="4.59" />
<input type="text" name="itemtotal[3]" value="0.99" />
<input type="text" name="itemquantity[3]" value="10" />
<input type="text" name="itemprice[3]" value="9.90" />
(1) User can change any itemprice[i] and/or itemquantity[i], so each needs a keyup. I can do that in php as it iterates over the items.
(2) These elements will have a $('.itemtotal[i]').keyup(calcgrand); (Or function other than calcgrand, if needed) statement, too. That keyup can be added by the php code as it evaluates the items in the cart.
(3) When an element is changed, then the script should automatically (a) calculate the $('[name="itemtotal[i]"]').val() and (b) replace the value for $('[name="itemtotal[i]"]').val().
(4) Then, the script above will use the $('[name="itemtotal[i]"]').val() to (a) replace the #subtotal value and (b) use that value in the equation.
Can someone help me with this? I am stuck on how to iterate over the [i] elements.
p.s. Any corrections/enhancements to the above code is appreciated, too.
Add a custom class to the desired inputs to sum:
HTML:
<input type="text" class="customclass" name=itemtotal[1] value="8.97" />
<input type="text" class="customclass" name=itemquantity[1] value="3" />
<input type="text" class="customclass" name=itemprice[1] value="2.99" />
JS:
var sum = 0;
$.each('.customclass',function(i, item){
sum = sum + Number($(this).val());
})
alert(sum);
if you for example group your inputs by giving them a class, or have each group in a div like so:
<!-- ordertotal = sum of #subtotal, #taxptotal, #shiptotal and #disctotal -->
<input type="text" id="ordertotal" name="ordertotal" value="106.49">
<input type="text" id="taxsptotal" name="taxsptotal" value="6.72">
<input type="text" id="shiptotal" name="shiptotal" value="15.83">
<input type="text" id="disctotal" name="disctotal" value="0.00">
<!-- sum of the cart "itemtotal[i]" -->
<input type="text" id="subtotal" name="subtotal" value="83.94">
<!-- cart items
User can change any itemprice[i] and/or itemquantity[i]
itemtotal[i] = sum(itemquantity[i] * itemprice[i])
-->
<div class="group">
<input type="text" name="itemtotal[1]" value="8.97" />
<input type="text" name="itemquantity[1]" value="3" />
<input type="text" name="itemprice[1]" value="2.99" />
</div>
<div class="group">
<input type="text" name="itemtotal[2]" value="4.59" />
<input type="text" name="itemquantity[2]" value="1" />
<input type="text" name="itemprice[2]" value="4.59" />
</div>
<div class="group">
<input type="text" name="itemtotal[3]" value="0.99" />
<input type="text" name="itemquantity[3]" value="10" />
<input type="text" name="itemprice[3]" value="9.90" />
</div>
Then you could do the following in javascript:
function calcSubTotal() {
$('[name^="itemtotal"]').each(function(i){
var sum = 0;
$('[name^="itemtotal"]').each(function(i){
sum += $(this).val();
});
$('#subtotal').val(sum);
});
}
$('.group').each(function(i) {
var total = $(this).find('[name^="itemtotal"]');
var qnt = $(this).find('[name^="itemquantity"]');
var price = $(this).find('[name^="itemprice"]');
total.keyup(function(e){
price.val(total.val() * qnt.val());
calcSubTotal();
});
qnt.keyup(function(e){
price.val(total.val() * qnt.val());
calcSubTotal();
});
});
$("[name^='itemprice'], [name^='itemquantity']").keyup(function(){
var input_name = $(this).attr('name');
var temp_name_split = input_name.split(/[\[\]]+/);
var temp_total = parseInt($('[name="itemquantity['+temp_name_split[1] +']"]').val()) * parseFloat($('[name="itemprice['+temp_name_split[1] +']"]').val());
$('[name="itemtotal['+temp_name_split[1]+']"]').val(temp_total.toFixed(2));
var total = 0;
$("[name^='itemtotal']").each(function() {
total += parseFloat($(this).val());
});
$('#subtotal').val(total.toFixed(2));
});

Categories