calculation of packing charges in java script - javascript

I have an tax invoice page for making invoice. I am using javascript for calculating the amount. I want to add courier charges in javascript. Can anybody help me?
Here is code
function calculateTotal() {
var totalAmount = 0;
$("[id^='price_']").each(function() {
var id = $(this).attr('id');
id = id.replace("price_", '');
var price = $('#price_' + id).val();
var quantity = $('#quantity_' + id).val();
if (!quantity) {
quantity = 1;
}
var total = price * quantity;
$('#total_' + id).val(parseFloat(total));
totalAmount += total;
});
$('#subTotal').val(parseFloat(totalAmount));
var taxRate = $("#taxRate").val();
var subTotal = $('#subTotal').val();
if (subTotal) {
var taxAmount = subTotal * taxRate / 100;
$('#taxAmount').val(taxAmount);
subTotal = parseFloat(subTotal) + parseFloat(taxAmount);
$('#totalAftertax').val(subTotal);
var amountPaid = $('#amountPaid').val();
var totalAftertax = $('#totalAftertax').val();
if (amountPaid && totalAftertax) {
totalAftertax = totalAftertax - amountPaid;
$('#amountDue').val(totalAftertax);
} else {
$('#amountDue').val(subTotal);
}
}

CSS is only for demo ( you can ignore it )
I added packaging fees & shipping fees with also FREE option each
$(document).ready(function() {
calculateTotal();
});
function calculateTotal() {
var totalAmount = 0;
$("[id^='price_']").each(function() {
var id = $(this).attr('id').replace("price_", '');
var price = $('#price_' + id).val();
var quantity = $('#quantity_' + id).val();
if (!quantity) {
quantity = 1;
}
var total = price * quantity;
$('#total_' + id).val(parseFloat(total));
totalAmount += total;
});
$('#subTotal').val(parseFloat(totalAmount));
var taxRate = parseFloat($("#taxRate").val());
var subTotal = parseFloat($('#subTotal').val());
if (subTotal) {
var taxAmount = subTotal * taxRate / 100;
$('#taxAmount').val(taxAmount);
subTotal = parseFloat(subTotal) + parseFloat(taxAmount);
$('#totalAftertax').val(subTotal);
var amountPaid = $('#amountPaid').val();
var totalAftertax = $('#totalAftertax').val();
if (amountPaid && totalAftertax) {
totalAftertax = totalAftertax - amountPaid;
$('#amountDue').val(totalAftertax);
} else {
$('#amountDue').val(subTotal);
}
var amoutDue = parseFloat($('#amountDue').val());
var shipping = parseFloat($('#shipping').val());
var packaging = parseFloat($('#packaging').val());
$('#amountDue').val(amoutDue + shipping + packaging);
}
}
[disabled],
[readonly] {
background-color: #eee;
border: 1px solid #ccc;
color: #888;
}
div {
padding: 5px 10px;
}
div:nth-child(even) {
background: #eee;
}
label {
display: inline-block;
width: 120px;
}
<div>
<input id="price_1" type="number" value="5" />
<input id="quantity_1" type="number" value="3" min="1" />
<input id="total_1" type="number" value="15" readonly />
</div>
<div>
<input id="price_3" type="number" value="15" />
<input id="quantity_3" type="number" value="1" min="1" />
<input id="total_3" type="number" value="15" readonly />
</div>
<div>
<input id="price_8" type="number" value="20" />
<input id="quantity_8" type="number" value="2" min="1" />
<input id="total_8" type="number" value="40" readonly />
</div>
<div align="center">
<button type="button" onclick="calculateTotal()">Update Cart</button>
</div>
<hr />
<div><label>Sub Total:</label>
<input id="subTotal" type="number" value="0" readonly /></div>
<div><label>Tax Rate:</label>
<input id="taxRate" type="number" value="15" readonly /></div>
<div><label>Tax Amount:</label>
<input id="taxAmount" type="number" value="0" readonly /></div>
<div><label>Total After Tax:</label>
<input id="totalAftertax" type="number" value="0" readonly /></div>
<div>
<label>Shipping:</label>
<select id="shipping" onchange="calculateTotal()">
<option value="0">Regular FREE ( 12-15 days )</option>
<option value="12.99">Express $12.99 ( 1-2 days )</option>
<option value="9.99">UPS $9.99 ( 2-3 days )</option>
<option value="6.99">DHL $6.99 ( 3-5 days )</option>
</select>
</div>
<div>
<label>Packaging:</label>
<select id="packaging" onchange="calculateTotal()">
<option value="0">Regular FREE</option>
<option value="2.99">Package 1 $2.99</option>
<option value="4.99">Package 2 $4.99</option>
<option value="7.99">Package 3 $7.99</option>
</select>
</div>
<div><label>Amount Paid:</label> <input id="amountPaid" type="number" value="15" readonly /></div>
<div><label>Amount Due:</label> <input id="amountDue" type="number" value="0" readonly /></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Related

How to dynamically select elements with document.querySelectorAll() for function call?

I have been working on this fiddle:
https://jsfiddle.net/j1vrb7to/165/
The code in that fiddle is this:
HTML:
<div id="CalculationContainer">
<input type="numbers" class="form-control new-tuition" /> <br />
<input type="numbers" class="form-control new-tuition" /> <br />
<input type="numbers" class="form-control new-tuition" /><br /><br />
<input type="numbers" id="new-tuition-total" disabled="disabled" /><br /> <br />
<input type="numbers" class="form-control new-state" /> <br />
<input type="numbers" class="form-control new-state" /> <br />
<input type="numbers" class="form-control new-state" /><br /><br />
<input type="numbers" id="new-state-total" disabled="disabled" />
</div>
JavaScript:
const NewTuitionInputs = document.querySelectorAll("div#CalculationContainer > input.new-tuition");
const NewStateInputs = document.querySelectorAll("div#CalculationContainer > input.new-state");
NewTuitionInputs.forEach(function(input) {
input.onchange = function() {
var total = 0;
NewTuitionInputs.forEach(function(input) {
total += parseInt(input.value);
});
document.getElementById("new-tuition-total").value = total;
}
});
NewStateInputs.forEach(function(input) {
input.onchange = function() {
var total = 0;
NewStateInputs.forEach(function(input) {
total += parseInt(input.value);
});
document.getElementById("new-state-total").value = total;
}
});
As the users enter values into the textboxes, I want to update the value of another field to display running totals. Ultimately I will need to keep track of 20+ running totals on my form. Instead of maintaining 20+ functions, is it possible to use a single function to calculate running totals on the fly? Here is some pseudocode to demonstrate what I'm thinking:
var ThisInput = document.querySelectorAll("div#CalculationContainer > input.[INPUT_CLASS_PARAMETER_HERE]");
ThisInput.forEach(function(input) {
input.onchange = function() {
var total = 0;
ThisInput.forEach(function(input) {
total += parseInt(input.value);
});
document.getElementById("[DYNAMICALLY_CHOOSE_WHERE_TO_DISPLAY").value = total;
}
});
You have a convention that the inputs have a class and then the total has an id with that class name plus -total. You can use this to your advantage in making a general purpose function:
function trackTotals(className){
var inputs = document.querySelectorAll(`div#CalculationContainer > input.${className}`);
inputs.forEach(input => {
input.addEventListener("change",()=>{
var total = [...inputs].reduce((acc,i) => acc + (parseInt(i.value,10) || 0),0);
document.getElementById(`${className}-total`).value = total;
})
})
}
Usage would then be:
trackTotals("new-tuition");
trackTotals("new-state");
// whatever else that follows same conventions
Live example follows:
trackTotals("new-tuition");
trackTotals("new-state");
function trackTotals(className){
var inputs = document.querySelectorAll(`div#CalculationContainer > input.${className}`);
inputs.forEach(input => {
input.addEventListener("change",()=>{
var total = [...inputs].reduce((acc,i) => acc + (parseInt(i.value,10) || 0),0);
document.getElementById(`${className}-total`).value = total;
})
})
}
<div id="CalculationContainer">
<input type="numbers" class="form-control new-tuition"/> <br/>
<input type="numbers" class="form-control new-tuition"/> <br/>
<input type="numbers" class="form-control new-tuition"/><br/><br/>
<input type="numbers" id="new-tuition-total" disabled="disabled"/><br /><br />
<input type="numbers" class="form-control new-state"/> <br/>
<input type="numbers" class="form-control new-state"/> <br/>
<input type="numbers" class="form-control new-state"/><br/><br/>
<input type="numbers" id="new-state-total" disabled="disabled"/>
</div>
Yes, you can create a function that takes the id:
function doTotal(name) {
var ThisInput = document.querySelectorAll(`div#CalculationContainer > input.${name}`);
ThisInput.forEach(function(input) {
input.onchange = function() {
var total = 0;
ThisInput.forEach(function(input) {
total += parseInt(input.value);
});
document.getElementById(`${name}-total`).value = total;
}
});
}
Note that I'm using string templates to build the selector strings.
You can use the event delegation method:
const calcContainer = document.getElementById('CalculationContainer')
, sumElms =
{ tuition: { sum: document.getElementById('new-tuition-total'), elms: [...document.querySelectorAll('input.new-tuition')] }
, state: { sum: document.getElementById('new-state-total'), elms: [...document.querySelectorAll('input.new-state')] }
}
;
calcContainer.oninput= ({target}) =>
{
if (!target.matches('.new-tuition, .new-state')) return
let sumElm = target.matches('.new-tuition') ? sumElms.tuition : sumElms.state
sumElm.sum.value = sumElm.elms.reduce((s,e)=>s+e.valueAsNumber,0)
}
#CalculationContainer input {
float: left;
clear:both;
width: 5em;
}
#CalculationContainer input:disabled {
margin-bottom: 1em;
font-weight: bold;
color:black;
}
<div id="CalculationContainer">
<input type="number" class="form-control new-tuition" value="0">
<input type="number" class="form-control new-tuition" value="0">
<input type="number" class="form-control new-tuition" value="0">
<input type="number" id="new-tuition-total" disabled="disabled" value="0">
<input type="number" class="form-control new-state" value="0">
<input type="number" class="form-control new-state"value="0">
<input type="number" class="form-control new-state"value="0">
<input type="number" id="new-state-total" disabled="disabled"value="0">
</div>

Why does form not reset (all fields and div of result) after click clear?

I want display div id="showResult" after click calculate button and clear all input and div id="showResult" after click clear button in a form. But clear button doesn't work after I click the button.
What's the problem? How can I solve this problem?
window.onload = function BMR() {
var gender = document.getElementById('gender');
var weight = document.getElementById('weight');
var height = document.getElementById('height');
var age = document.getElementById('age');
var calculate = document.getElementById('calculate');
calculate.addEventListener('click', toBmr);
function toBmr() {
var select = null;
if (gender.value && weight.value && height.value && age.value) {
if (document.getElementById('gender').checked) {
select = document.getElementById('gender').value;
}
if (select == 'male') {
var result = (10 * weight.value) + (6.25 * height.value) - (5 * age.value) + 5;
document.getElementById('result').innerHTML = Number(result).toFixed(2);
} else {
var result = (10 * weight.value) + (6.25 * height.value) - (5 * age.value) - 161;
document.getElementById('result').innerHTML = Number(result).toFixed(2);
}
document.getElementById('showResult').style.display = "block";
} else {
result = " ";
}
};
};
function clearForm() {
document.getElementById("do-form").reset();
}
<form name="do-form" id="do-form">
<p>BMR Calculator</p>
<p>Gender:
<input type="radio" id="gender" name="gender" value="male" checked="checked">Male
<input type="radio" id="gender" name="gender" value="female">Female
</p>
<p>Weight: <input type="number" name="weight" id="weight" size="10" maxlength="6" onkeypress="if(this.value.length > 5) return false;"> kg</p>
<p>Height: <input type="number" name="height" id="height" size="10" maxlength="6" onkeypress="if(this.value.length > 5) return false;"> cm</p>
<p>Age: <input type="number" name="age" id="age" size="10" maxlength="3" onkeypress="if(this.value.length > 2) return false;"></p>
<button type="button" id="calculate">Calculate</button>
<button type="button" id="clear" onclick="clearForm()">Clear</button><br><br>
<div class="row-result-tab" id="showResult" style="display:none;">
<label>BMR = <span id="result"></span> calories/day</label>
</div>
</form>
You needed to hide the div in the clearForm
Here is your code cleaned up based on the DRY principle (don't repeat yourself)
We could get rid of some testing if we could trust the browser to respect the type="number" which is fairly well supported
window.addEventListener("load", () => {
document.getElementById('calculate').addEventListener('click', toBmr);
});
const toBmr = () => {
const gender = document.querySelector('[name=gender]:checked').value;
// the "number" fields will not allow other data than numbers
let weight = +document.getElementById('weight').value;
let height = +document.getElementById('height').value;
let age = +document.getElementById('age').value;
if (weight && age && height) {
let result = (10 * weight) + (6.25 * height) - (5 * age)
result += gender === 'male' ? 5 : -161; // add 5 for male, subtract 161 if female
document.getElementById('result').innerHTML = result.toFixed(2);
document.getElementById('showResult').style.display = "block";
}
};
const clearForm = () => {
document.getElementById("do-form").reset();
document.getElementById('showResult').style.display = "none";
}
<form name="do-form" id="do-form">
<p>BMR Calculator</p>
<p>Gender:
<input type="radio" name="gender" value="male" checked="checked">Male
<input type="radio" name="gender" value="female">Female
</p>
<p>Weight: <input type="number" name="weight" id="weight" size="10" maxlength="6" onkeypress="if(this.value.length > 5) return false;"> kg</p>
<p>Height: <input type="number" name="height" id="height" size="10" maxlength="6" onkeypress="if(this.value.length > 5) return false;"> cm</p>
<p>Age: <input type="number" name="age" id="age" size="10" maxlength="3" onkeypress="if(this.value.length > 2) return false;"></p>
<button type="button" id="calculate">Calculate</button>
<button type="button" id="clear" onclick="clearForm()">Clear</button><br><br>
<div class="row-result-tab" id="showResult" style="display:none;">
<label>BMR = <span id="result"></span> calories/day</label>
</div>
</form>
The result div can not auto hide, you need add code to hide it
document.getElementById('showResult').style.visibility = "hidden";
or
document.getElementById('showResult').style.display= "none";
window.onload = function BMR() {
var gender = document.getElementById('gender');
var weight = document.getElementById('weight');
var height = document.getElementById('height');
var age = document.getElementById('age');
var calculate = document.getElementById('calculate');
calculate.addEventListener('click', toBmr);
function toBmr() {
var select = null;
if (gender.value && weight.value && height.value && age.value) {
if (document.getElementById('gender').checked) {
select = document.getElementById('gender').value;
}
if (select == 'male') {
var result = (10 * weight.value) + (6.25 * height.value) - (5 * age.value) + 5;
document.getElementById('result').innerHTML = Number(result).toFixed(2);
} else {
var result = (10 * weight.value) + (6.25 * height.value) - (5 * age.value) - 161;
document.getElementById('result').innerHTML = Number(result).toFixed(2);
}
document.getElementById('showResult').style.display = "block";
} else {
result = " ";
}
};
};
function clearForm() {
document.getElementById("do-form").reset();
//document.getElementById('showResult').style.visibility = "hidden";
document.getElementById('showResult').style.display = "none";
}
<form name="do-form" id="do-form">
<p>BMR Calculator</p>
<p>Gender:
<input type="radio" id="gender" name="gender" value="male" checked="checked">Male
<input type="radio" id="gender" name="gender" value="female">Female
</p>
<p>Weight: <input type="number" name="weight" id="weight" size="10" maxlength="6" onkeypress="if(this.value.length > 5) return false;"> kg</p>
<p>Height: <input type="number" name="height" id="height" size="10" maxlength="6" onkeypress="if(this.value.length > 5) return false;"> cm</p>
<p>Age: <input type="number" name="age" id="age" size="10" maxlength="3" onkeypress="if(this.value.length > 2) return false;"></p>
<button type="button" id="calculate">Calculate</button>
<button type="button" id="clear" onclick="clearForm()">Clear</button><br><br>
<div class="row-result-tab" id="showResult" style="display:none;">
<label>BMR = <span id="result"></span> calories/day</label>
</div>
</form>
I took some time to improve your code. As given in other answers already. You need to set the display of your result html back to none.
window.onload = function BMR() {
// Init
var gender = document.getElementById('gender');
var weight = document.getElementById('weight');
var height = document.getElementById('height');
var age = document.getElementById('age');
var calculate = document.getElementById('calculate');
// Click handler
calculate.addEventListener('click', toBmr);
function toBmr() {
// Init
// Very good practice to first declare your vars
// However include result as well here
// Remove select because it's not doing anything
var result = "";
var penalty = 0;
if (gender.value && weight.value && height.value && age.value && gender.checked) {
// When you have duplicate code, check the difference!
// Only the penalty given at the end is different!
if (gender.value == 'male') {
penalty = 5;
} else {
penalty = -161;
}
// Now we calculate with one formula
result = (10 * weight.value) + (6.25 * height.value) - (5 * age.value) + penalty;
// Add to html
document.getElementById('result').innerHTML = Number(result).toFixed(2);
document.getElementById('showResult').style.display = "block";
}
};
};
function clearForm() {
// This resets the form fields
document.getElementById("do-form").reset();
// This remove result again
document.getElementById('showResult').style.display = "none";
}
<form name="do-form" id="do-form">
<p>BMR Calculator</p>
<p>Gender:
<input type="radio" id="gender" name="gender" value="male" checked="checked">Male
<input type="radio" id="gender" name="gender" value="female">Female
</p>
<p>Weight: <input type="number" name="weight" id="weight" size="10" maxlength="6" onkeypress="if(this.value.length > 5) return false;"> kg</p>
<p>Height: <input type="number" name="height" id="height" size="10" maxlength="6" onkeypress="if(this.value.length > 5) return false;"> cm</p>
<p>Age: <input type="number" name="age" id="age" size="10" maxlength="3" onkeypress="if(this.value.length > 2) return false;"></p>
<button type="button" id="calculate">Calculate</button>
<button type="button" id="clear" onclick="clearForm()">Clear</button><br><br>
<div class="row-result-tab" id="showResult" style="display:none;">
<label>BMR = <span id="result"></span> calories/day</label>
</div>
</form>

Textbox value not being multiplied when checkbox selected (HTML & Javascript/JQuery)

My code updates the CPC textbox when options are selected, but when an agency discount is selected (i.e. the 10% checkbox), it successfully lowers the CPC textbox value by 10% but does not do the same for the Total Cost textbox.
The Total Cost textbox value should be the (CPC textbox value * number of clicks textbox) * percentdiscount multiplier
Can anyone see where I'm going wrong? I'll be happy to clarify further if I haven't explained this very well!
HTML:
<div class="runningtotal">
Running CPC Total (in £): <input id="sum" type="text" readonly="true" value="0.00" data-total="0" />
Total Cost (in £): <input id="totalcost" type="text" readonly="true" value="0 (until clicks specified)" data-total="0" />
</div>
<div class="black_whitelisting">
<h1>4. Blacklist/Whitelist?</h1>
<input type="checkbox" class="blacklist" name="blacklist" value="0.20" id="blacklist_checkbox" onclick="BlacklistFunction()">Blacklist required<br>
<input type="checkbox" class="whitelist" name="whitelist" value="0.30" id="whitelist_checkbox">Whitelist required<br>
</div>
<div class="selecttier">
<h1>5. Number of Clicks</h1>
<input id="numberofclickstextbox" type="text" value="0.00" data-total="0" oninput="calculatetier()" />
</div>
<div class="agencydiscount">
<h1>6. Agency Discount</h1>
<label>
<input type="radio" name="percentdiscount" value="1" checked>
None
</label>
<label>
<input type="radio" name="percentdiscount" id="10percent" value="0.9" onclick="calculatetotalcost10()" >
10% Discount
</label>
<label>
<input type="radio" name="percentdiscount" id="15percent" value="0.85" onclick="calculatetier15()" >
15% Discount
</label>
</div>
Javascript:
jQuery(function($) {
$('input[name="percentdiscount"]').on('change', function() {
applyDiscount();
});
$('input[type=checkbox]').click(function() {
let sum = 0;
$('input[type=checkbox]:checked').each(function() {
sum += parseFloat($(this).val());
});
$('#sum').val(sum.toFixed(2)).data('total', sum);
applyDiscount();
});
function applyDiscount() {
var pc = parseFloat($('input[name="percentdiscount"]:checked').val());
$('#sum').val(function() {
return ($(this).data('total') * pc).toFixed(2);
});
}
});
//to work out total cost
function calculatetier() {
var myBox5 = document.getElementById('numberofclickstextbox').value;
var myBox6 = document.getElementById('sum').value;
var result = document.getElementById('totalcost');
var myResult = myBox5 * myBox6;
result.value = myResult.toFixed(2);
}
Looks like you are calculatetier function isn't being called during the change of discount.
Working Demo: https://codepen.io/punith/pen/gOpaVxr?editors=1010
HTML code
<div class="runningtotal">
Running CPC Total (in £): <input id="sum" type="text" readonly="true" value="0.00" data-total="0" />
Total Cost (in £): <input id="totalcost" type="text" readonly="true" value="0 (until clicks specified)" data-total="0" />
</div>
<div class="black_whitelisting">
<h1>4. Blacklist/Whitelist?</h1>
<input type="checkbox" class="blacklist" name="blacklist" value="0.20" id="blacklist_checkbox" >Blacklist required<br>
<input type="checkbox" class="whitelist" name="whitelist" value="0.30" id="whitelist_checkbox">Whitelist required<br>
</div>
<div class="selecttier">
<h1>5. Number of Clicks</h1>
<input id="numberofclickstextbox" type="text" value="0.00" data-total="0" oninput="calculatetier()" />
</div>
<div class="agencydiscount">
<h1>6. Agency Discount</h1>
<label>
<input type="radio" name="percentdiscount" value="1" checked>
None
</label>
<label>
<input type="radio" name="percentdiscount" id="10percent" value="0.9" >
10% Discount
</label>
<label>
<input type="radio" name="percentdiscount" id="15percent" value="0.85" >
15% Discount
</label>
</div>
JS Code
function calculatetier() {
var myBox5 = document.getElementById('numberofclickstextbox').value;
var myBox6 = document.getElementById('sum').value;
var result = document.getElementById('totalcost');
if(myBox6=="0.00"){
myBox6 =1;
}
console.log(myBox6)
var myResult = myBox5 * myBox6;
result.value = myResult.toFixed(2);
}
jQuery(function($) {
$('input[name="percentdiscount"]').on('change', function() {
applyDiscount();
});
$('input[type=checkbox]').click(function() {
let sum = 0;
$('input[type=checkbox]:checked').each(function() {
sum += parseFloat($(this).val());
});
$('#sum').val(sum.toFixed(2)).data('total', sum);
applyDiscount();
});
//to work out total cost
function applyDiscount() {
var pc = parseFloat($('input[name="percentdiscount"]:checked').val());
$('#sum').val(function() {
return ($(this).data('total') * pc).toFixed(2);
});
calculatetier()
}
});
try to use onchange event instead I guess the event you are binding is not correct
<input id="numberofclickstextbox" type="text" value="0.00" data-total="0" onchange="calculatetier()" />

vuejs form Calcuations in LAravel Array

I have an issue I know might be basic but has been giving me a headache. Any help is highly appreciated
I have a form named timesheets looping through a dates array in laravel. I am trying to add up form fields hour + hour1 + hour2 and I want them added up and displayed in the total_hours field.
My problem is only the top row gets added(i don't get any errors in the web console)
!https://imgur.com/gNdJVNE
//app.js code
el: '#timesheet',
data: function(){
return {
hour: '',
hour1: '',
hour2: '',
hour3: '',
hour4: '',
hour5: '',
total_hours: ''
};
},
computed: {
TotalTimesheets: function() {
return (this.hour + this.hour1 + this.hour2 + this.hour3 + this.hour4 + this.hour5)
}
}
//my _form.blade.php code:
#foreach($dates as $date)
<strong>{{$date->date}}</strong>
<input type="text" name="hour[]" value="0" id="hour" v-model.number="hour" class="form-control">
#if(empty($analysis->act1))
#else
<input type="text" name="hour1[]" value="0" id="hour1" v-model.number="hour1" class="form-control>
#endif
#if(empty($analysis->act2))
#else
<input type="text" name="hour2[]" value="0" id="hour2" v-model.number="hour2" class="form-contro">
#endif
#if(empty($analysis->act3))
#else
<input type="text" name="hour3[]" value="0" id="hour3" v-model.number="hour3" class="form-control">
#endif
#if(empty($analysis->act4))
#else
<input type="text" name="hour4[]" value="0" id="hour4" v-model.number="hour4" class="form-control">
#endif
#if(empty($analysis->act5))
#else
<input type="text" name="hour5[]" value="0" id="hour5" v-model.number="hour5" class="form-control">
#endif
<input type="text" name="total_hours[]" :value="TotalTimesheets" id="total_hours" class="form-control" max="9" >
#endforeach
<div class="form-group">
<button type="submit" class="btn btn-primary btn-lg">{{ $buttonText }}</button>
</div>
I will give you only a guide. This is just a "pseudo code" I did not check it.
Firstly, you need to create a component to render only one row of your sheet. Something like:
<template>
<div>
<strong>{{date}}</strong>
<div v-for="(hour, index) in hours" :key="index" >
<input type="text" v-model.number="hour.value">
</div>
<input type="text" :value="total">
</div>
</template>
<script>
export default{
name: 'ActiveHoursRow'
props:['date','hours'],
computed:{
total(){
return this.hours.reduce((a, v) => a + v);
}
}
}
</script>
Secondly, you need to create a component that renders the whole sheet with the help of row-rendering component.
<template>
<div v-for="(row, index) in backendData">
<ActiveHoursRow :date="row.date" :hours="row.hours" />
</div>
</template>
<script>
export default{
name: 'ActiveHoursRow'
data: function(){
return {
"backendData":[
#foreach($dates as $date)
{
"date":"{{$date->date}}",
"hours": [
#if(empty($analysis->act1))
#else
{"name":"12_07_2019_act1", "value": 0},
#endif
#if(empty($analysis->act2))
#else
{"name":"12_07_2019_act2", "value": 0},
#endif
]
},
#endforeach
]
}
}
}
</script>
It also always better to draw data as JSON in and then use it. It is more clear to understand and later you can easily to switch to dynamic loading.
See more about components: https://v2.vuejs.org/v2/guide/components.html
thanks for the help, but I decided to use Jquery as shown below.
$(document).on("keyup change paste", "td > input.auto-calc", function() {
row = $(this).closest("tr");
h = parseFloat(row.find("td input.hour").val()) || 0;
h1 = parseFloat(row.find("td input.hour1").val()) || 0;
h2 = parseFloat(row.find("td input.hour2").val()) || 0;
h3 = parseFloat(row.find("td input.hour3").val()) || 0;
h4 = parseFloat(row.find("td input.hour4").val()) || 0;
h5 = parseFloat(row.find("td input.hour5").val()) || 0;
row.find(".total_hours").val(h + h1 + h2 + h3 + h4 + h5);
var sum = 0;
var sum1 = 0;
var sum2 = 0;
var sum3 = 0;
var sum4 = 0;
var sum5 = 0;
var sum6 = 0;
$("input.total_hours").each(function() {
sum += +$(this).val();
});
$("input.hour").each(function() {
sum1 += +$(this).val();
});
$("input.hour1").each(function() {
sum2 += +$(this).val();
});
$("input.hour2").each(function() {
sum3 += +$(this).val();
});
$("input.hour3").each(function() {
sum4 += +$(this).val();
});
$("input.hour4").each(function() {
sum5 += +$(this).val();
});
$("input.hour5").each(function() {
sum5 += +$(this).val();
});
$("#total-month").text(sum);
$("#total-hour").text(sum1);
$("#total-hour1").text(sum2);
$("#total-hour2").text(sum3);
$("#total-hour3").text(sum4);
$("#total-hour4").text(sum5);
$("#total-hour5").text(sum6);
});
var i = 0;
$('.addy').on('click', function () {
++i;
addy();
});
function addy(){
var tr='<tr>'
+'<td><input type="text" name="timesheets['+i+'][date]" id="date[]" class="form-control " data-provide="datepicker" autocomplete="off"><input type="hidden" id="analysis_id" name="timesheets['+i+'][analysis_id]" value="{{$analysis->analysisid}}">'
+'<input type="hidden" id="activity_id5" name="timesheets['+i+'][activity_id5]" value="{{#$tact6->activity_id5}}"><input type="hidden" id="activity_id4" name="timesheets['+i+'][activity_id4]" value="{{#$tact5->activity_id4}}"><input type="hidden" id="activity_id3" name="timesheets['+i+'][activity_id3]" value="{{#$tact4->activity_id3}}"><input type="hidden" id="activity_id2" name="timesheets['+i+'][activity_id2]" value="{{#$tact3->activity_id2}}"><input type="hidden" id="activity_id1" name="timesheets['+i+'][activity_id1]" value="{{#$tact2->activity_id1}}"><input type="hidden" id="activity_id" name="timesheets['+i+'][activity_id]" value="{{#$tact1->activity_id}}"></td>'
+'<td><input type="text" name="timesheets['+i+'][hour]" value="0" id="hour" class="form-control hour auto-calc"></div></td>'
+'#if(empty($analysis->act1)) #else <td><input type="number" name="timesheets['+i+'][hour1]" value="0" id="hour1" class="form-control hour1 auto-calc" min="0" max="8"></div></td>#endif'
+'#if(empty($analysis->act2)) #else <td><input type="number" name="timesheets['+i+'][hour2]" value="0" id="hour2" class="form-control hour2 auto-calc" min="0" max="8"></div></td>#endif'
+'#if(empty($analysis->act3)) #else <td><input type="number" name="timesheets['+i+'][hour3]" value="0" id="hour3" class="form-control hour3 auto-calc" min="0" max="8"></div></td>#endif'
+'#if(empty($analysis->act4)) #else <td><input type="number" name="timesheets['+i+'][hour4]" value="0" id="hour4" class="form-control hour4 auto-calc" min="0" max="8"></div></td>#endif'
+'#if(empty($analysis->act5)) #else <td><input type="number" name="timesheets['+i+'][hour5]" value="0" id="hour5" class="form-control hour5 auto-calc" min="0" max="8"></div></td>#endif'
+'<td><div class="input-group mb-3"><div class="input-group-prepend"><span class="input-group-text"><i class="fa fa-list-ol"></i></span></div><input type="text" name="timesheets['+i+'][total_hours]" id="total_hours" class="form-control total_hours" max="9" ></div><input type="hidden" id="approved" name="timesheets['+i+'][approved]" value="No"> <input type="hidden" id="approved_by" name="timesheets['+i+'][approved_by]" value="{{$approved->supervisor_id}}"></td>'
+'<td><button type="button" class="btn btn-danger remove">Remove</button></td>'
+'</tr>'
$('tbody').append(tr);
};
$('body').on('click','.remove', function () {
var last=$('tbody tr').length;
$(this).parent().parent().remove();
});

Javascript Unit converter lb to kg

I am trying to implement a weight converter that takes pounds(lb) and converts it to kg and vice-versa in the total, I can't seem to get the logic of it right, here is my code, I don't want to use any libraries or frameworks because I want to learn the fundamentals of JavaScript, and also don't know how to implement the discount option.
Here is what I was able to do.
var appleWeight = +document.getElementById('weight1').value;
var orangeWeight = +document.getElementById('weight2').value;
var grapeWeight = +document.getElementById('weight3').value;
var bananaWeight = +document.getElementById('weight4').value;
var totalWeight = appleWeight + orangeWeight + grapeWeight + bananaWeight;
document.getElementById('total_weight').innerHTML = totalWeight;
console.log(totalWeight)
var applePrice = +document.getElementById('price1').value;
var orangePrice = +document.getElementById('price2').value;
var grapePrice = +document.getElementById('price3').value;
var bananaPrice = +document.getElementById('price4').value;
var totalPrice = applePrice + orangePrice + grapePrice + bananaPrice;
var discount = document.getElementById('discount').value;
var discountAmount = (totalPrice * Number(discount)) / 100
var finalPrice = totalPrice - discountAmount
document.getElementById('total_price').innerHTML = finalPrice;
console.log("total price " + totalPrice)
var lb = document.getElementsByTagName('select'.value)
<h1>JS Grocery Shop</h1>
<span class="label">Apple</span> <input type="number" name="weight" id="weight1" value="3.5" />
<select><option>kg</option><option class="lb" value="lb">lb</option></select> # $<input type="number" name="price" id="price1" value="2.3" /><br />
<span class="label">Orange</span><input type="number" name="weight" id="weight2" value="5" />
<select><option>kg</option><option class="lb" value="lb">lb</option></select> # $<input type="number" name="price" id="price2" value="3.0" /><br />
<span class="label">Grape</span> <input type="number" name="weight" id="weight3" value="2.0" />
<select><option>kg</option><option class="lb" value="lb">lb</option></select> # $<input type="number" name="price" id="price3" value="1.5" /><br />
<span class="label">Banana</span><input type="number" name="weight" id="weight4" value="1" />
<select><option>kg</option><option class="lb" value="lb">lb</option></select> # $<input type="number" name="price" id="price4" value="0.5" /><br /> Discount : <select id="discount">
<option value="0">0</option>
<option value="5">5%</option>
<option value="10">10%</option>
<option value="15">15%</option>
<option value="20">20%</option>
</select>
<br><br> Total Price : <span id="total_price"></span><br /> Total Weight : <span id="total_weight"></span>

Categories

Resources