Trying to get the total to generate from quantity and price - javascript

I've been working on this for a little longer then needed, but I can't find what is going wrong here. I think I've looked at it way too long. I need to get the items to add up after quantity is add to the form.
Here is my HTML
<div class="row-fluid container-cart">
<div class="span4">
<div class="thumbnail">
<img src="http://myurl.com/image.jpg" />
<div class="caption">
<h3 class="">Title</h3>
<p class="">Description</p>
<div class="row-fluid">
<div class="span6">
<p class="lead">
<span id="item-price">100</span>
<span class="price-integer">
<input type="hidden" value="100">
</span>
</p>
</div>
<div class="span6">
<span>Quantity</span>
<input type="text" name="" id="quantity" class="stored quantity" autocomplete="off" value="">
</div>
<div class="span6">
<input type="text" name="base-total" id="base-total" class="stored readonly base-total" value="" readonly>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="span6">
Total:
<span class="total-cart">
<input type="text" name="total-cart" id="total-cart" class="stored readonly" value="" disabled="disabled">
</span>
</div>
Here is my JS
$('.quantity').on('keyup', function() {
var sum = 0;
$(".container-cart").each(function(i,o){
total = parseInt($(o).find(".quantity input").val(), 10) * parseInt($(o).find(".price-integer input").val(), 10);
if(!isNaN(total) /*&& total.length!=0**/) {
$(o).find(".base-total").val(total);
sum += total;
}
});
$("#total-cart").val(sum);
});

Looks like you typed a wrong selector, it's the .quantity input, the .quantity is an input, so it won't have any children, maybe you want to mean the input.quantity which means finding the input having class quantity.
Demo.

Related

how to display form with div correctly?

I have this part of form field
When user click on the Add button will copy the above form field and user can add more in this field .
but when I add <div id="ownership"> above the code form it start to look like this
I need to put id=ownership because I want to use it in my jQuery function
<div id="ownership">
<div class="col-lg-12 mb-30 ">
<label for="add_owner"><b><span style="color:#e60000;">*</span> Name</b></label><br>
<input class="from-control" type="text" id="name" >
</div>
<div class="col-lg-6 mb-30" >
<label for="add_owner"><b><span style="color:#e60000;">*</span> Phone number</b></label><br>
<div class="input-group-prepend">
<input class="from-control" type="text" id="phone" >
</div>
</div>
<div class="col-lg-6 mb-30" >
<label for="add_owner"><b><span style="color:#e60000;">*</span> Emailn</b></label><br>
<div class="input-group-prepend">
<input class="from-control" type="email" id="email">
</div>
</div>
</div>
<div id="owner"></div>
<br>
<div class="col-md-12">
<button type="button" class="btn btn-success w-30 add_info f-r">Add</button>
</div>
<script>
$(document).ready(function(){
$(".add_info").click(function(){
var newForm = $("#ownership").clone();
$('input', newForm).val('');
$('owner').append(newForm);
});
});
</script>
How do I fix the code in order to achieve the image in number 1 ?
try this
<div class="row">
<div class="col-sm-6"> Text</div>
<div class="col-sm-6"> Text</div>
</div>
you need to apply this format then design will be properly according your desirable.
Try this way. Always use bootstrap col class inside row class then it will not cause unexpected result.
<div class="row">
<div class="col-md-12"></div>
<div class="col-md-6"></div>
<div class="col-md-6"></div>
</div>

How to calculate total with AutoNumeric

I'm using http://autonumeric.org/ or https://github.com/autoNumeric/autoNumeric/blob/master/README.md
How to fix
When I use JS function to calculate the sum total appear, but not as formatted AutoNumeric as I want it to be
When mouse hover the calculated field, it disappears
var taxRate = 0.10
function calculateAmount() {
var elemsAmount = document.getElementsByName("tAmount")
var total = 0
elemsAmount.forEach(function(e){
total += Number(e.value.replace(',',''))
})
document.getElementById("total").value = total
document.getElementById("tax").value = total*taxRate
document.getElementById("finalTotal").value = total+total*taxRate
}
document.getElementById("tableBox").addEventListener("change",calculateAmount)
new AutoNumeric.multiple('[contenteditable="true"]', 'dotDecimalCharCommaSeparator')
<script src="https://unpkg.com/autonumeric" type="text/javascript"></script>
<div id="tableBox">
<div name="tableRow">
<div class="col s3">
<div class="input-field">
<input type="text" name="tAmount" contenteditable="true">
<label>input</label>
</div>
</div>
</div> <!-- name tableRow -->
<div name="tableRow">
<div class="col s3">
<div class="input-field">
<input type="text" name="tAmount" contenteditable="true">
<label>input</label>
</div>
</div>
</div> <!-- name tableRow -->
</div> <!-- id tableBox -->
Auto JS Calculation fields
<div class="input-field">
<input type="text" id="total" contenteditable="true">
<label for="total">Total</label>
</div>
<div class="input-field">
<input type="text" id="tax" contenteditable="true">
<label for="tax">Tax</label>
</div>
<div class="input-field">
<input type="text" id="finalTotal" contenteditable="true">
<label for="finalTotal">Final Total</label>
</div>
Expect output #,###.##<br>
Also the problem is when mouse hover on the Calculation field, it disappears
Thank you in advance
You should initialise and save the Autonumeric fields and use the Autonumeric API to update the value using .set().
You can do the same with the input fields and use .getNumber() to do your calculations.
As far as I know you can safely remove the contenteditable="true" attribute from <input/> elements — these are designed to be "editable".
const taxRate = 0.10
const config = 'dotDecimalCharCommaSeparator'
const totalInput = new AutoNumeric('#total', config)
const taxInput = new AutoNumeric('#tax', config)
const finalTotalInput = new AutoNumeric('#finalTotal', config)
const elemsAmount = new AutoNumeric.multiple('[name="tAmount"]', config)
const tableBox = document.getElementById('tableBox')
function calculateAmount() {
let total = 0
elemsAmount.forEach(function(e) {
total += e.getNumber()
})
totalInput.set(total)
taxInput.set(total * taxRate)
finalTotalInput.set(total + total * taxRate)
}
tableBox.addEventListener('change', calculateAmount)
<script src="https://unpkg.com/autonumeric" type="text/javascript"></script>
<div id="tableBox">
<div name="tableRow">
<div class="col s3">
<div class="input-field">
<input type="text" name="tAmount">
<label>input</label>
</div>
</div>
</div>
<div name="tableRow">
<div class="col s3">
<div class="input-field">
<input type="text" name="tAmount">
<label>input</label>
</div>
</div>
</div>
</div>
Auto JS Calculation fields
<div class="input-field">
<input type="text" id="total">
<label for="total">Total</label>
</div>
<div class="input-field">
<input type="text" id="tax">
<label for="tax">Tax</label>
</div>
<div class="input-field">
<input type="text" id="finalTotal">
<label for="finalTotal">Final Total</label>
</div>

Auto submit form information without page reload

I have a form with a bunch of number fields, all these fields serves the purpose to be added to each other through php. The only problem is that for the numbers to actually be submitted and make the php function work, I have to click the submit button which reloads the page. While this actually does work it is a bit annoying, that it has to reload and at the same time it removes the numbers from the actual form, so the user can't see where he/she has entered their numbers.
I know it is possible in some way to make it submit automatically, but is it possible to make the php function get the form information every time a user enters something, so that the new total sum would be automatically updated, thus not having to reload?
I have my php and html in the same script, but for the case of this question I have split them into two parts.
PHP part
<?php
$amount_s_bp = $_POST['amountSmallBP'];
$amount_m_bp = $_POST['amountMedBP'];
$amount_l_bp = $_POST['amountLargeBP'];
$amount_xl_bp = $_POST['amountXLBP'];
$amount_s_wp = $_POST['amountSmallWP'];
$amount_m_wp = $_POST['amountMedWP'];
$amount_l_wp = $_POST['amountLargeWP'];
$amount_xl_wp = $_POST['amountXLWP'];
$amount_s_bs = $_POST['amountSmallBS'];
$amount_m_bs = $_POST['amountMedBS'];
$amount_l_bs = $_POST['amountLargeBS'];
$amount_xl_bs = $_POST['amountXLBS'];
$amount_s_bt = $_POST['amountSmallBT'];
$amount_m_bt = $_POST['amountMedBT'];
$amount_l_bt = $_POST['amountLargeBT'];
$amount_xl_bt = $_POST['amountXLBT'];
$shirt_price = 150;
$amount_total = $amount_s_bp + $amount_m_bp + $amount_l_bp + $amount_xl_bp + $amount_s_wp + $amount_m_wp + $amount_l_wp + $amount_xl_wp + $amount_s_bs + $amount_m_bs + $amount_l_bs + $amount_xl_bs + $amount_s_bt + $amount_m_bt + $amount_l_bt + $amount_xl_bt;
$price_total = $amount_total * $shirt_price;
?>
Form part
As you can see I have a bunch of number inputs and then at the end I have a "total" area where the total sum should be displayed using <?php echo $price_total; ?> and <?php echo $amount_total; ?>.
<form action="index.php" method="post" id="orderForm" onsubmit="return checkCheckBoxes(this);">
<div class="row">
<div class="col-xs-6">
<div class="bpShirtDesign">
<span id="bpShirtOformT">Sort Polka</span><br>
<span id="sBP">Small</span>
<div id="firstName">
<input type="number" id="amount" name="amountSmallBP" placeholder="Antal"/>
</div>
<span id="mP">Medium</span>
<div id="firstName">
<input type="number" id="amount" name="amountMedBP" placeholder="Antal"/>
</div>
<span id="lBP">Large</span>
<div id="firstName">
<input type="number" id="amount" name="amountLargeBP" placeholder="Antal"/>
</div>
<span id="xlBP">X-Large</span>
<div id="firstName">
<input type="number" id="amount" name="amountXLBP" placeholder="Antal"/>
</div>
</div>
</div>
<div class="col-xs-6">
<div class="wpShirtDesign">
<span id="bpShirtOformT">Hvid Polka</span><br>
<span id="sBP">Small</span>
<div id="firstName">
<input type="number" id="amount" name="amountSmallWP" placeholder="Antal"/>
</div>
<span id="mP">Medium</span>
<div id="firstName">
<input type="number" id="amount" name="amountMedWP" placeholder="Antal"/>
</div>
<span id="lBP">Large</span>
<div id="firstName">
<input type="number" id="amount" name="amountLargeWP" placeholder="Antal"/>
</div>
<span id="xlBP">X-Large</span>
<div id="firstName">
<input type="number" id="amount" name="amountXLWP" placeholder="Antal"/>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-xs-6">
<div class="bsShirtDesign">
<span id="bpShirtOformT">Bla Stribet</span><br>
<span id="sBP">Small</span>
<div id="firstName">
<input type="number" id="amount" name="amountSmallBS" placeholder="Antal"/>
</div>
<span id="mP">Medium</span>
<div id="firstName">
<input type="number" id="amount" name="amountMedBS" placeholder="Antal"/>
</div>
<span id="lBP">Large</span>
<div id="firstName">
<input type="number" id="amount" name="amountLargeBS" placeholder="Antal"/>
</div>
<span id="xlBP">X-Large</span>
<div id="firstName">
<input type="number" id="amount" name="amountXLBS" placeholder="Antal"/>
</div>
</div>
</div>
<div class="col-xs-6">
<div class="btShirtDesign">
<span id="bpShirtOformT">Bla Tattersall</span><br>
<span id="sBP">Small</span>
<div id="firstName">
<input type="number" id="amount" name="amountSmallBT" placeholder="Antal"/>
</div>
<span id="mP">Medium</span>
<div id="firstName">
<input type="number" id="amount" name="amountMedBT" placeholder="Antal"/>
</div>
<span id="lBP">Large</span>
<div id="firstName">
<input type="number" id="amount" name="amountLargeBT" placeholder="Antal"/>
</div>
<span id="xlBP">X-Large</span>
<div id="firstName">
<input type="number" id="amount" name="amountXLBT" placeholder="Antal"/>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-3">
</div>
<div class="col-md-6">
<div class="bgTotals">
<input type="submit" value="Submit" id="submitValues">
<span id="totalAmount" class="h3">I alt antal = </span><?php echo $amount_total; ?><br>
<span id="totalPrice" class="h3">I alt pris = </span> <?php echo $price_total; ?><span> DKK</span>
</div>
</div>
<div class="col-md-3">
</div>
</div>
</form>
You don't need a server-side script for this kind of processing. Just prevent that the form is submitted with:
<button type="button">Button</button>
Then, using javascript, retrieve the value of each form and perform calculations.
//Gets the value
var value = document.getElementById('myid')
//Repeat that last line until all values are retrieved
...
//Make your calculations
var result = value + value2 //... etc
//Display your result
document.getElementById('resultid').textContent = result;
Although, if you are going to sum a lot of elements, it might be better to give the same class to those elements, so you can do this:
var elements = document.getElementsByClassName('myclassname');
var sum = 0;
for (var i=0, max=elements.length; i < max; i++) {
sum = sum + parseInt(elements.item(i).textContent);
}
UPDATE
To add an event listener to every input you can iterate over every element or you could associate a listener to a parent element like this:
document.getElementById('myParentElement').addEventListener('input', function() {
return update();
}, false);
And you should throw all the code that retrieves the values from the inputs, perform the calculations and updates the DOM in the update() function, which will get called every time an input changes.
First things first, you have the id "amount" on all of your inputs. This will not work, an id can only be used once per page. So, figure out a convention to make these id's unique. Like id='field1-id' or something. Also, remove the action and method attributes from your form tag. They'll be unneeded at this point.
Then you can use jQuery and an AJAX call to do what you are looking for. Something like:
$("#submitValues").bind('click', function(e){
var formData[];
$("#orderForm").each('input[^="-id"]', function(){
formData.push($(this).val());
});
$.ajax({
url: 'index.php',
data: formData
}).success(function(response){
$("totalAmount").val(response.returnedTotalAmount);
$("totalPrice").val(response.returnedTotalPrice);
}).fail(function(response){
/* do something else */
});
e.preventDefault();
});
Mind you this code is untested, and very hastily written but it should give you the general idea of how to accomplish what you're after.

Getting value from repeating HTML data with JavaScript

I have repeating data that gets injected into the html like this:
<div class="subFormContent" id="Results">
<div class="subFormContentRow">
<div class="subFormContentRowChildWrapper">
<div id="subCtrlPreviewRow1-identifier" class="subCtrlPreviewRowContainer">
<div id="subCtrlRow1column1-identifier" class="subCtrlPreviewCell">
<div class="subCtrlPreviewCtrlHolder">
<div class="control ">
<label class="block label alignLabel">
<span>value</span>
</label>
<input type="text" class="textInput block field" id="value-identifier" value="value1" />
</div>
</div>
</div>
<div id="subCtrlRow1column2-identifier" class="subCtrlPreviewCell">
<div class="subCtrlPreviewCtrlHolder">
<div class="control">
<label class="block label alignLabel">
<span>propName</span>
</label>
<input type="text" class="textInput block field" id="propName-identifier" value="propname1" />
</div>
</div>
</div>
</div>
</div>
</div>
</div>
...Repeats
I need to get the value from column 1 where column 2 is equal to x with JavaScript or jquery, but it will not always be on the same row number. It will however only have one row where column 2 is x. Can anyone think of a way to do this?
updated for multiple rows
1.2 update if id's starts with words "value" and "propName"
$(document).ready(function(){
var x = 5,
row = $('.subFormContentRow');
row.each(function(index, el){
var inputProp = $(el).find('[id^="propName"]'),
inputVal = $(el).find('[id^="value"]');
if(inputProp.val() == x){
alert(inputVal.val());
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="subFormContent" id="Results">
<div class="subFormContentRow">
<div class="subFormContentRowChildWrapper">
<div id="subCtrlPreviewRow1-identifier" class="subCtrlPreviewRowContainer">
<div id="subCtrlRow1column1-identifier" class="subCtrlPreviewCell">
<div class="subCtrlPreviewCtrlHolder">
<div class="control">
<label class="block label alignLabel">
<span>value</span>
</label>
<input type="text" class="textInput block field" id="value-456456456" value="value1" />
</div>
</div>
</div>
<div id="subCtrlRow1column2-identifier" class="subCtrlPreviewCell">
<div class="subCtrlPreviewCtrlHolder">
<div class="control">
<label class="block label alignLabel">
<span>propName</span>
</label>
<input type="text" class="textInput block field" id="propName-45647898778645656" value="5" />
</div>
</div>
</div>
</div>
Shouldn't be using ids in a way that they show up multiple times on the page.
You can still do it by finding the element, traversing back up to the row, then finding the value.
With JQuery:
$("#propName[value='" + x + "']")
.closest(".subFormContentRow").find("#value").val();

How can I get output in input box or html element with jQuery?

$(document).ready(function() {
$('form').submit(function() {
var principle = $("#principle").val();
var rate = $("#rate").val();
var time = $("#time").val();
var interest = principle * rate * time / 100;
interest = $("p").append(interest);
return false;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<div class="table commonTable">
<div class="row">
<div class="cell">
<label for="P">Principal (P): $</label>
</div>
<div class="cell">
<input name="P" id="principle" value="10,000.00" class="nmbr_real real" type="text" title="positive real number" placeholder="amount" required="" />
</div>
</div>
<div class="row">
<div class="cell">
<label for="R">Rate (R): %<br />
<span class="note small">per year</span></label
>
</div>
<div class="cell">
<input
name="R"
id="rate"
value="3.875"
class="nmbr_real real"
type="text"
title="positive real number"
placeholder="rate"
required=""
/>
</div>
</div>
<div class="row">
<div class="cell">
<label for="t">Time (t):</label>
</div>
<div class="cell">
<input name="t" id="time" value="5" class="nmbr_real real" type="text" title="0 or positive real number" placeholder="#" required="" />
</div>
</div>
</div>
<button>Calculate</button>
</form>
just create inputbox
<input type="text" id="abc" name="price" value="" />
and use below code for insert value in inputbox
jQuery(document).ready(function($) {
$("#abc").val('100');
});
If you want to get the output in input box the use val() function.
$("input").val(interest);
If you want to get the output in HTML element the use html() function.
$("p").html(interest);
For setting a value in textbox use val()
$('#abc').val('13');
For setting a value in 'p' use text()
<p id='p_Id'></p>
$('#p_Id').text('13');

Categories

Resources