set default checked value at total cost display without using "value" - javascript

As we can directly set the value to the value we wanted in the textbox like <input type="text" name="total" value="500" size="10" readonly />
Is there any method to display the default checked value in the text box wihout using value = "500"??
var checks = document.getElementsByName('deliveryType');
for (var i = 0; i < checks.length; i++) checks[i].onclick = function() {
var cal = document.getElementsByName('deliveryType');
var total = 0;
for (var i = 0; i < cal.length; i++) {
if (cal[i].checked) {
total += parseFloat(cal[i].getAttribute("data-price"));
}
}
document.getElementsByName("total")[0].value = "$" + total.toFixed(2);
}
<form id= selectEvent>
<section id="collection">
<p>
Home - £500.00 <input type="radio" name="deliveryType" value="home" data-price="500.00" checked /> |
self collect - no charge <input type="radio" name="deliveryType" value="ticketOffice" data-price="0" />
</p>
</section>
<section id="checkCost">
<h2>Total cost</h2>
Total <input type="text" name="total" size="10" readonly />
</section>
</form>

Try the following code:
var checks = document.getElementsByName('deliveryType');
checks.forEach(function(value){
if(value.checked){
document.getElementsByName("total")[0].value = "$" + value.getAttribute('data-price');
}
})
for (var i = 0; i < checks.length; i++) checks[i].onclick = function() {
var cal = document.getElementsByName('deliveryType');
var total = 0;
for (var i = 0; i < cal.length; i++) {
if (cal[i].checked) {
total += parseFloat(cal[i].getAttribute("data-price"));
}
}
document.getElementsByName("total")[0].value = "$" + total.toFixed(2);
}
<form id= selectEvent>
<section id="collection">
<p>
Home - £500.00 <input type="radio" name="deliveryType" value="home" data-price="500.00" checked /> |
self collect - no charge <input type="radio" name="deliveryType" value="ticketOffice" data-price="0" />
</p>
</section>
<section id="checkCost">
<h2>Total cost</h2>
Total <input type="text" name="total" size="10" readonly />
</section>
</form>

Related

How can I add up my selection lists, radios, and checkboxes to total?

I need some guidance in how to add my selection list to my total. I am still new to javascript so i did what i could but for some reason, i cannot figure out how to add the selection list to my total. the textboxes with 0.00 are there for me to see if the radios, checkboxes and selection are adding up properly.
``
`
function customerInfo(cName){
var dinerName = document.getElementById(cName).value;
document.getElementById('cust_name').innerHTML = dinerName;
}
// format val to n number of decimal places
function formatDecimal(val, n) {
n = n || 2;
var str = "" + Math.round ( parseFloat(val) * Math.pow(10, n) );
while (str.length <= n) {
str = "0" + str;
}
var pt = str.length - n;
return str.slice(0,pt) + "." + str.slice(pt);
}
function getRadioVal(form, name) {
var radios = form.elements[name];
var val;
for (var i=0, len=radios.length; i<len; i++) {
if ( radios[i].checked == true ) {
val = radios[i].value;
break;
}
}
return val;
}
function getToppingsTotal(e) {
var form = this.form;
var val = parseFloat( form.elements['tops_tot'].value );
if ( this.checked == true ) {
val += parseFloat(this.value);
} else {
val -= parseFloat(this.value);
}
form.elements['tops_tot'].value = formatDecimal(val);
updatePizzaTotal(form);
}
function getSizePrice(e) {
this.form.elements['sz_tot'].value = parseFloat( this.value );
updatePizzaTotal(this.form);
}
function getDeliveryPrice(e){
selectElement = document.querySelector('#pick_delivery');
output = selectElement.options[selectElement.selectedIndex].value;
console.log(output);
}
function updatePizzaTotal(form) {
var sz_tot = parseFloat( form.elements['sz_tot'].value );
var tops_tot = parseFloat( form.elements['tops_tot'].value );
form.elements['total'].value = formatDecimal( sz_tot + tops_tot );
}
// removes from global namespace
(function() {
var form = document.getElementById('pizzaForm');
var el = document.getElementById('pizza_toppings');
// input in toppings container element
var tops = el.getElementsByTagName('input');
for (var i=0, len=tops.length; i<len; i++) {
if ( tops[i].type === 'checkbox' ) {
tops[i].onclick = getToppingsTotal;
}
}
var sz = form.elements['size'];
for (var i=0, len=sz.length; i<len; i++) {
sz[i].onclick = getSizePrice;
}
// set sz_tot to value of selected
form.elements['sz_tot'].value = formatDecimal( parseFloat( getRadioVal(form, 'size') ) );
updatePizzaTotal(form);
})(); // end remove from global namespace and invoke
<form name="pizzaOrder" method="post" id="pizzaForm" enctype="text/plain">
<fieldset style="width: 60%;">
<legend>Create Your Pizza</legend>
<h3>Customer's Name:</h3>
<p>
<input type="text" name="client_name" id="client_name" value="First and Last Name" size="30" value="" />
<input type="button" onclick="customerInfo('client_name')" value="Enter"></button>
</p>
<h3>Pick Your Size:</h3>
<p>
<label><input type="radio" name="size" value="8" /> Small</label>
<label><input type="radio" name="size" value="10" /> Medium</label>
<label><input type="radio" name="size" value="12" /> Large</label>
<label><input type="radio" name="size" value="14" checked/> Extra Large</label>
<input type="text" name="sz_tot" value="0.00" />
</p>
<h3>Pick Your Toppings</h3>
<p id="pizza_toppings">
<label><input type="checkbox" name="Pineapple" value="1.50" /> Pineapple</label>
<label><input type="checkbox" name="Onions" value="1.50" /> Onions </label>
<label><input type="checkbox" name="Ham" value="1.50" /> Ham</label>
<label><input type="checkbox" name="Sausage" value="1.50" /> Sausage</label>
<label><input type="checkbox" name="Pepperoni" value="1.50" /> Pepperoni</label>
<input type="text" name="tops_tot" value="0.00" />
</p>
<h3>Delivery Or Pick Up</h3>
<p>
<select class="delivery" id="pick_delivery" size="2">
<option value="0">Pick Up: Free</option>
<option value="2">Delivery: $2</option>
</select>
<input type="button" onclick="getDeliveryPrice()" id="delivery_pick" value="enter" /></button>
</p>
<p>
<label>Total: $ <input type="text" name="total" class="num" value="0.00" readonly="readonly" /></label>
</p>
<p>
<input type="button" value="Confirm" />
<input type="button" value="Cancel">
</p>
</fieldset>
</form>
<div>
<h2>Your Order:</h2>
<p>
<h4>Your Name: <span id="cust_name"> </span></h4>
<h4>Your Pizza Size:</h4>
<h4>Toppings Selected:</h4>
</p>
</div>
</fieldset>
</form>```
On the bottom of the page the results should look similar to this:
Your Name: Pam Love
Pizza Size Selected: Extra Large
Toppings Selected: Bacon, Pineapple, Ham
Total: 20.50
When clicked on confirm order, the onclick button should redirect the page to a new tab that says:
Your order will be ready in 20 minutes.
or if cancelled then the user clicks the cancel button also redirected to a new tab:
Your order is cancelled.
You can just use some css selectors to accomplish most of this.
Here is how you can get your selected size:
document.querySelector('input[type="radio"][name="size"]:checked').value
And here is how you can get the list of toppings:
[...document.querySelectorAll('input[type="checkbox"][name="topping"]:checked')].map((t) => t.value).join(', ')
The remaining things should be pretty easy to find using querySelector or getElementById

How to calculate tax in salary

I am working on a payroll project in which I want to calculate overtime, allowance and tax to salary. I want to add overtime and allowance to salary and subtract tax from salary.
The following script works with overtime and allowance but I'm facing problems with calculating tax.
When I enter a tax percentage it should calculate the tax amount from the salary to the tax field and calculate the total. When I enter the tax directly it should calculate the percentage to the taxPercentage field and calculate the total.
$(document).on('change keyup blur', '.add', function(e) {
add();
});
function add() {
salary = $('#salary').val();
allowance = $('#allowance').val() || 0;
over = $('#over').val() || 0;
prevTotal = $('#total').val() || 9000;
if (allowance > 0 || over > 0) {
total = parseFloat(salary) + parseFloat(allowance) + parseFloat(over);
$('#total').val(total);
} else {
$('#total').val(prevTotal);
}
}
$(document).on('change keyup blur', '.tax', function(e) {
subtracttax();
});
function subtracttax() {
salary = $('#salary').val();
taxPercentage = $('#taxPercentage').val() || 0;
tax = $('#tax').val() || 0;
prevTotal = $('#total').val() || 9000;
if (taxPercentage > 0) {
total = parseFloat(salary) * parseFloat(taxPercentage) / 100;
$('#tax').val(total);
$('#total').val(prevTotal - total);
} else {
$('#total').val(prevTotal);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<div>
<label> salary </label>
<input type="text" id="salary" value="9000" />
</div>
<br>
<div>
<label> over Time </label>
<input type="text" class="add" id="over" />
</div>
<br>
<div>
<label> allowance </label>
<input type="text" class="add" id="allowance" />
</div>
<br>
<div>
<label> Tax Percentage</label>
<input type="text" class="tax" id="taxPercentage" />
</div>
<br>
<div>
<label> Total Tax</label>
<input type="text" class="tax" id="tax" />
</div>
<br>
<div>
<label> Total salary</label>
<input type="text" id="total" />
</div>
Try like this.
as per your comment I only added salary + over time.
calculateTax();
$(document).on('change keyup blur', '.tax', function(e) {
calculateTax();
});
$(document).on('change keyup blur', '.taxVal', function(e) {
calculateTaxPer();
});
function calculateTax() {
salary = $('#salary').val();
allowance = $('#allowance').val() || 0;
over = $('#over').val() || 0;
total = (parseFloat(salary) + parseFloat(allowance) + parseFloat(over)) || 0;
taxPercentage = $('#taxPercentage').val() || 0;
tax = $('#tax').val() || 0;
$('#total').val(total);
if (taxPercentage > 0) {
totalTax = (parseFloat(salary) + parseFloat(over)) * parseFloat(taxPercentage) / 100;
$('#tax').val(totalTax);
$('#total').val(total - totalTax);
return false;
}
}
function calculateTaxPer(){
salary = $('#salary').val();
allowance = $('#allowance').val() || 0;
over = $('#over').val() || 0;
total = (parseFloat(salary) + parseFloat(allowance) + parseFloat(over)) || 0;
taxPercentage = $('#taxPercentage').val() || 0;
tax = $('#tax').val() || 0;
$('#total').val(total);
if(tax > 0){
taxPer = (parseFloat(tax)/(parseFloat(salary) + parseFloat(over)))*100;
$('#taxPercentage').val(taxPer);
$('#total').val(total - tax);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<div>
<label> salary </label>
<input type="text" id="salary" value="9000" />
</div>
<br>
<div>
<label> over Time </label>
<input type="text" class="tax" id="over" />
</div>
<br>
<div>
<label> allowance </label>
<input type="text" class="tax" id="allowance" />
</div>
<br>
<div>
<label> Tax Percentage</label>
<input type="text" class="tax" id="taxPercentage" />
</div>
<br>
<div>
<label> Total Tax</label>
<input type="text" class="taxVal" id="tax" />
</div>
<br>
<div>
<label> Total salary</label>
<input type="text" id="total" />
</div>
change this line in subtracttax function
prevTotal = $('#total').val() || 9000;
to
prevTotal = parseFloat(salary) + parseFloat(allowance) + parseFloat(over);
Problem is you are overriding the total value once the tax value is entered. Instead you should calculate totals each time you make changes.

add additional value to the total

I am looking for a way to add the value from (discount) and (quantity) to my total. As for discount part, the customer will need to enter the right code to receiver discount. And for quantity, when clicked at the checkbox, then change the quantity, the total will also follow. Can you guys help me out on this problem?
thanks
(sorry, my English is not good)
function addItemPrice() {
var total = 0;
var count = 0;
for (var i = 0; i < document.myform.item.length; i++) {
if (document.myform.item[i].checked) {
total = (total + document.myform.item[i].value * 1); // another way to convert string to number
count++;
}
}
return total;
}
var sh_prices = new Array();
sh_prices["standard"] = 10;
sh_prices["express"] = 20;
function getAddShipping() {
var shippingPrice = 0;
var theForm = document.forms["myform"];
var shipping = theForm.elements["shipping"]
for (var i = 0; i < shipping.length; i++) {
if (shipping[i].checked) {
shippingPrice = sh_prices[shipping[i].value];
break;
}
}
return shippingPrice;
}
function getCode() {
var theForm = document.forms["myform"];
var discode = theForm.elements["discount"]
if (discode == "UAC123") {
alert("yes");
} else {
alert("no")
}
}
function getTotal() {
var totalPrice = getAddShipping() + addItemPrice();
document.getElementById('Price').innerHTML = "the total price" + totalPrice;
}
<form name="myform">
Sickle $5 <input type="checkbox" name="item" value="5" onclick="getTotal(item)">
<input type="number" name="quantity"><br> Sickle $1 <input type="checkbox" name="item" value="1" onclick="getTotal(item)">
<input type="number" name="quantity" value="1"><br> Sickle $50 <input type="checkbox" name="item" value="50" onclick="getTotal(item)">
<input type="number" name="quantity" value="1"><br> Sickle $5 <input type="checkbox" name="item" value="5" onclick="getTotal(item)">
<input type="number" name="quantity" value="1"><br> Sickle $7 <input type="checkbox" name="item" value="7" onclick="getTotal(item)">
<input type="number" name="quantity" value="1"><br> Standard
<input type="radio" name="shipping" value="standard" onClick="getTotal(shipping)" /> Express
<input type="radio" name="shipping" value="express" onClick="getTotal(shipping)" /> <br> Discount code
<input type="text" name="discount" size=15>
<input type="button" id="code" value="check" onClick="getCode(code)">
<div id="Price">
</div>
</form>

Output form within html page

I want to print the submitted input elements within the same page below the html form. The checked checkbox elements should all be printed. The image element can be avoided.
The function does not seem to be working.
function validateForm(myForm) {
var a = document.getElementById("fname").value;
document.getElementById("display").innerHTML = y;
var b = document.getElementByName("passwords").value;
document.getElementById("display1").innerHTML = y;
var c = document.getElementByName("gender");
var i;
for (i = 0; i < c.length; ++i) {
if (c[i].checked)
document.getElementById("display1").innerHTML = c[i].value; //looping through radio buttons
}
var d = document.getElementByName("hobbies");
for (i = 0; i < d.length; ++i) {
if (d[i] checked)
ans = ans + d[i].value; //looping through checkboxes and adding to display in display 2 id.
}
document.getElementById("display2").innerHTML = ans;
var e = document.getElementByName("cities").value;
document.getElementById("display3").innerHTML = e;
}
<form name="myForm">
<fieldset>
<legend>Personal Details</legend>
Name:
<input type="text" id="fname" <br>Password:
<input type="password" name="password" id="passwords" />
<br>Gender:
<input type="radio" name="gender" />Male
<input type="radio" name="gender" />Female</input>
<br>Hobbies:
<input type="radio" name="hobbies" value="Reading" />Reading
<input type="radio" name="hobbies" value="Writing" />Writing</input>
<br>City:
<select name="cities" />
<option>Surat</option>
<option>Ahmedabad</option>
<option>Rajkot</option>
<option>Vadodra</option>
</select>
<br>Image:
<input type="file" accept="image/*" value="image" style="margin:0px 10px 10px 100px; margin:absolute;" />
</form>
<br>
<input type="Submit" value="Submit" onSubmit="validateform(myForm);">
</fieldset>
<p id="display"></p>//display the values submitted within the html page
<p id="display1"></p>
<p id="display2"></p>
<p id="display3"></p>
getElementsByName - plural and when accessing the first, use [0] like
document.getElementsByName("cities")[0].value
missing a dot in d[i].checked
move the onSubmit="validateform(myForm);" to the form tag and do onSubmit="return validateForm(this);" and add return false;
validateForm misspelled in event handler (lower case f)
y missing
ans not defined
function validateForm(myForm) {
var a = document.getElementById("fname").value;
document.getElementById("display").innerHTML = a;
var b = document.getElementsByName("passwords").value;
document.getElementById("display1").innerHTML = a;
var c = document.getElementsByName("gender");
var i, ans;
for (i = 0; i < c.length; ++i) {
if (c[i].checked)
document.getElementById("display1").innerHTML = c[i].value; //looping through radio buttons
}
var d = document.getElementsByName("hobbies");
for (i = 0; i < d.length; ++i) {
if (d[i].checked)
ans = ans + d[i].value; //looping through checkboxes and adding to display in display 2 id.
}
document.getElementById("display2").innerHTML = ans;
var e = document.getElementsByName("cities")[0].value;
document.getElementById("display3").innerHTML = e;
return false; // normally when error but here to stay on page
}
<form name="myForm" onSubmit="return validateForm(this);">
<fieldset>
<legend>Personal Details</legend>
Name:
<input type="text" id="fname" <br>Password:
<input type="password" name="password" id="passwords" />
<br>Gender:
<input type="radio" name="gender" />Male
<input type="radio" name="gender" />Female</input>
<br>Hobbies:
<input type="radio" name="hobbies" value="Reading" />Reading
<input type="radio" name="hobbies" value="Writing" />Writing</input>
<br>City:
<select name="cities" />
<option>Surat</option>
<option>Ahmedabad</option>
<option>Rajkot</option>
<option>Vadodra</option>
</select>
<br>Image:
<input type="file" accept="image/*" value="image" style="margin:0px 10px 10px 100px; margin:absolute;" />
</form>
<br>
<input type="Submit" value="Submit">
</fieldset>
<p id="display"></p><!-- display the values submitted within the html page -->
<p id="display1"></p>
<p id="display2"></p>
<p id="display3"></p>

Finding the total or average from four input fields and displaying the value in another input field

I'm trying to use JS to get the sum or the average of four numbers from an input field and then displaying that in another text field. There's a radio button to choose if it's the total or average that is to be displayed.
Here is my html for the form:
<form name="calculate">
Mark: <input type="number" name="number" id="num1"><br>
Mark: <input type="number" name="number" id="num2"><br>
Mark: <input type="number" name="number" id="num3"><br>
Mark: <input type="number" name="number" id="num4"><br>
<input type="radio" id="numTotal" name="choice" value="total">Find total</input>
<input type="radio" id="numAvg" name="choice" value="average">Find average</input>
<br>
<input type="submit" form="calculate" value="Submit" onclick="calculate();">
<input type="reset" form="calculate" value="Reset">
<br>
Result: <input type="text" name="result" id="result" value="" disabled>
</form>
And down here is my JS code:
function calculate(){
var arr = document.getElementsByName("number");
var tot = 0;
var av = 0;
for(var i = 0; i < arr.length; i++) {
if(parseInt(arr[i].value)){
tot += parseInt(arr[i].value);
}
}
av = tot/arr.length;
if(document.getElementById("numTotal").checked) {
document.calculate.getElementbyId("result").value = tot;
}
if(document.getElementById("numAvg").checked) {
document.getElementbyId("result").value = av;
}
}
After running this, the result input field doesn't show the input. Is the error in my script or in the html or both?
<script type="text/javascript">
function calculateFunc() {
var arr = document.getElementsByName("number");
var tot = 0;
var av = 0;
for (var i = 0; i < arr.length; i++) {
if (parseInt(arr[i].value)) {
tot += parseInt(arr[i].value);
}
}
av = tot / arr.length;
if (document.getElementById("numTotal").checked) {
document.getElementById("result").value = tot;
}
if (document.getElementById("numAvg").checked) {
document.getElementById("result").value = av;
}
return false;
}
</script>
<div class="form">
<form name="calculate">
Mark: <input type="number" name="number" id="num1"><br>
Mark: <input type="number" name="number" id="num2"><br>
Mark: <input type="number" name="number" id="num3"><br>
Mark: <input type="number" name="number" id="num4"><br>
<input type="radio" id="numTotal" name="choice" value="total">Find total</input>
<input type="radio" id="numAvg" name="choice" value="average">Find average</input>
<br>
<br>
Result: <input type="text" name="result" id="result" value="" disabled>
</form>
<input type="submit" value="Submit" onclick="calculateFunc();">
<input type="reset" value="Reset">
</div>
This is work for me in Chrome :)
document.calculate.getElementbyId("result").value = tot;
if(document.getElementById("numTotal").checked) {
document.calculate.getElementbyId("result").value = tot;
}
if(document.getElementById("numAvg").checked) {
document.getElementbyId("result").value = av;
}
need to replace
document.getElementbyId("result").value = tot;
if(document.getElementById("numTotal").checked) {
document.calculate.getElementById("result").value = tot;
}
if(document.getElementById("numAvg").checked) {
document.getElementById("result").value = av;
}

Categories