jQuery/Javascript complex iterate over elements - javascript

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));
});

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>

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>

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" />

How to get a value and label in a textbox

function radioVal(){
//var radVal = document.mainForm.rads.value;
var radVal = document.getElementsByName("rads").value;
result.innerHTML = 'You selected: '+radVal;
}
<div class="pres">
<input type="radio" id="radio01" name="rads" value="10" checked />
<label for="radio01" class="dis"><span>1 time service</span></label>
</div>
<div class="pres">
<input type="radio" id="radio02" name="rads" value="20" />
<label for="radio02" class="dis"><span>Every week</span></label>
</div>
<div class="pres">
<input type="radio" id="radio03" name="rads" value="15" />
<label for="radio03" class="dis"><span>Every 2 weeks </span></label>
</div>
<div class="pres">
<input type="radio" id="radio04" name="rads" value="10" />
<label for="radio04" class="dis"><span>Every 4 weeks</span></label>
</div>
<input type="text" value="" id="result" name="perce" />
<input type="text" value="" id="txtservV" name="servicename" />
<input type="text" value="" id="final_pay" name="final_pay" />
Hello i am using this function to get the value of a selected radio button in a textfield name perce and its value in a field name servicename any one help me in it to sourt it out. I am using this function in doucument.ready function.
Use Document.getElementsByName function which returns array of elements (or better collection, array-like object), so that you can access value of input by index (0 in your case):
var perceVal = document.getElementsByName("perce")[0].value
In case of radio buttons you have to iterate through elements and find which one is checked:
var rads = document.getElementsByName("rads");
var radsValue;
for (var i = 0; i < rads.length; i++) {
if (rads[i].checked) {
radsValue = rads[i].value // here is checked radio
break;
}
}

How to get key (index) value of a textbox in array textboxes

I want a jQuery function or javascript that alert the index and the value of array textboxes : e.g.
<input type="text" name="textbox[]" value="1" onblur="javascriptfunction(this.value,this.index)" />
<input type="text" name="textbox[]" value="foo" onblur="javascriptfunction(this.value,this.index)" />
<input type="text" name="textbox[]" value="banana" onblur="javascriptfunction(this.value,this.index)" />
Whenever mouse moves for example from the first input I have this alerted (1,0) and second is (foo,1) and so on. I couldn't find the function that does that. Please help.
You can use jQuery index() and val() like
$('input').blur(function(){
alert($(this).val() + ',' + ($(this).index()-1));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<input type="text" name="textbox[]" value="1" />
<input type="text" name="textbox[]" value="foo" />
<input type="text" name="textbox[]" value="banana" />
Update
To target certain elements or have this in a named function, first, put identifiers on your elements such as a class my-class. Then, make a named function and pass it to the jQuery blur function
$('.my-class').blur( alertIndexAndVal );
function alertIndexAndVal(){
alert($(this).val() + ',' + ($(this).index()-1));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<input class="my-class" type="text" name="textbox[]" value="1" />
<input class="my-class" type="text" name="textbox[]" value="foo" />
<input class="my-class" type="text" name="textbox[]" value="banana" />
var textboxes = $('input[name="textbox[]"]');
textboxes.on('blur', function() {
var index = textboxes.index( this );
alert( this.value + ', ' + index );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" name="textbox[]" value="1" />
<input type="text" name="textbox[]" value="foo" />
<input type="text" name="textbox[]" value="banana" />
I figured I'd post a javascript solution which to be honest attempts to do something like the index function of jquery although i think jquery function might be better.
var getIndexValue = function (e) {
var children = e.parentElement.children;
for (var i = 0; i < children.length; i++) {
if (children[i] == e) {
alert("Index: " + (i+1) + ", Value: " + e.value);
}
}
}
<div>
<input type="text" name="textbox[]" value="one" onblur="getIndexValue(this)">
<input type="text" name="textbox[]" value="two" onblur="getIndexValue(this)">
<input type="text" name="textbox[]" value="three" onblur="getIndexValue(this)">
</div>
Index: (i+1)
Value: (e.value);

Categories