How make automatic calculate - javascript

How to calculate using jquery or Javascript in Codeigniter as below requirement
I have 3 input element to calculate after user complete they form element :
1, Quantity
2, Unitprice
3, Total.
By Total = quantity * unitprice.
<td><?php echo form_input('quantity','',' class="form-control"')?></td>
<td><?php echo form_input('unitprice','',' class="unit form-control" placeholder="unit pricee"')?></td>
<td><?php echo form_label('','total','class="form_control"')?></td>
I try to write javascript like this
<script type="text/javascript">
$(document).ready(function () {
$('.unitprice').keyup(function () {
Calculate();
});
});
function Calculate() {
var quantity = document.getElementsByClassName("quantity").val();
var unitprice = document.getElementsByClassName("unitprice").val();
var total = quantity * unitprice;
$('.total').val(total);
}
</script>
But it is not work
Thanks advance!!!!

Try like this:
$(function(){
$('.qty, .unit').on('blur', function(e){
var qty = parseFloat( $('.qty').val() ),
unit = parseFloat( $('.unit').val() );
if( isNaN(qty) || isNaN(unit) ) {
$('.result').text('');
return false;
}
var total = qty * unit;
$('.result').text( total );
});
});
DEMO

Here's a basic example, since I was bored. Fiddle - http://jsfiddle.net/sgnl/44ts8ucf/1/
html
<input type="text" id="quantity" class="calc_element"> Quantity
<input type="text" id="unit_price" class="calc_element"> Unit Price
<div id="total"></div>
javascript
// get some IDs or classes on your elements to target them easily
var total = $('#total');
// bind an event that triggers on KEYUP
$('.calc_element').on('keyup', function(){
// when triggered get the values from the input elements
// via jQuery's '.val()' method
var quantity = $('#quantity').val() || 1;
var unit_price = $('#unit_price').val();
var result = (quantity * unit_price) + " total";
// set the innerHTML of the div to your calculated total
total.html(result);
});
YMMV, thats the jist of it, some tweaking will need to be down for your code.

Related

Subtract amount on form submit JavaScript / JQuery

I have a checkout page, where I would like to implement a new feature: subtract from total cart value a certain amount, introduced in an input.
Example: There is 1 item in cart, with value of 10.00$. If user typed 100 in that input, then he would have a discount of 1$ (100 pts = 1$ in this example) and the final value of the cart would be 9.00$. Since I'm using some integrated apps for getting/calculating item value, total cart value, etc. I would like to get some generic code, which I would eventually adjust, to link with my existing code, functions, etc.
The function I have should have these features:
create form
get input value
subtract used points from user's total amount (for example totalPts = 1000)
subtract from cart total value used points, converted into $ (100pts = 1$)
For now, my function looks like this:
function appendRefferalPoints() {
const totalPts = 1000;
// creating form - ok
$form = $('<form id="refForm" class="coupon-form" action></form>');
$form.append(
'<input type="text" id="refValue" name="refInput" class="coupon-value input-small" >'
);
$form.append('<button type="submit" class="btn">Aplica</button>');
$("body").append($form);
// get input value - not ok
$("#refForm").submit(function () {
let value = 0;
$.each($("#refForm").serializeArray(), function (i, field) {
value[field.name] = field.value;
});
});
// subtraction from totalPts logic - not ok
let rez = totalPts - value;
console.log("Final Rez: " + rez);
// subtraction converted pts from cart value logic
}
Now when I submit the form I only url changes from /checkout#/cart to /checkout/?refInput=512#/cart
function appendRefferalPoints() {
const totalPts = 1000;
let cartValue=10;
let discount=0;
let inputValue = 0;
// creating form - ok
$form = $('<form id="refForm" class="refForm coupon-form" ></form>');
$form.append(
'<input type="text" id="refValue" name="refInput" class="coupon-value input-small" value="100" >'
);
$form.append('<button id="btnClick" class="btn">Aplica</button>');
$("body").append($form);
$(document).on("submit", "#refForm", function(e){
//getting input value while submitting form
inputValue=$("#refValue").val();
//converting 100 pts to 1 dallor
discount=inputValue/100;
//calculating balance pts
let balancePts = totalPts - parseInt(inputValue);
//calculating final amount
let finalCartValue=cartValue-discount;
alert("finalCartValue"+finalCartValue);
});
}
appendRefferalPoints();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

Calculate data to an input field from 2 select fields with javascript

I want to calculate 2 options from different selects in HTML and display the result in an input field. The first select will fill from a mysql database, the second select will fill with 1 option that is the pair of the first. I want to multiply them and display the result in the last input field. Here is an example:
The table of the database the field are "id product"-id quantity price type
table view
Here is the result that i want: to display
When the user selects the quantity the corresponding value is going to be displayed to the next field.
After that in the last input field i want to calculate the previous selections
the user can only select the quantity and not the price
I made a select with php and made an array which is converted to javascript array object
<?php
$sth = $conn->prepare("SELECT quantity,price FROM eb_products_price WHERE product_id = 20");
$sth->execute();
/* Fetch all of the remaining rows in the result set */
print("Fetch all of the remaining rows in the result set:\n");
$result = $sth->fetchAll(PDO::FETCH_COLUMN|PDO::FETCH_GROUP);
$json_array = json_encode($result);
print_r($result);
With this code the only thing i can do is to display the quantity with a foreach
BUT the price will remain the last one and it wont change while i change the quantity.
I found a way to display the correct price but with javascript here is the code
<script>
var arrayObjects = {"400":["0.8"],"300":["0.9"],"200":["0.95"],"100":["1.1"]}
function products() {
var quantity= document.getElementById("quantity");
var price= document.getElementById("price");
var arrprice = quantity.options[quantity.selectedIndex].value;
while (price.options.length) {
price.remove(0);
}
var prices = arrayObjects[arrprice];
if (prices) {
var i;
for (i = 0; i < prices.length; i++) {
var price1 = new Option(prices[i], i);
price.options.add(price1);
}
}
}
</script>
Here is the calculate function that work without the last part of code:
calculate = function()
{
var quantity= document.getElementById('quantity').value;
var price= document.getElementById('price').value;
var number = parseFloat(quantity)*parseFloat(price);
var n = number.toFixed(2);
document.getElementById('result').value = n
}
To change a HTML-Element dynamically you need event Listeners like onChange example below:
var arrayObjects = {"400":["0.8"],"300":["0.9"],"200":["0.95"],"100":["1.1"]}
function products() {
var quantity = document.getElementById("quantity");
var factor = document.getElementById("factor"); // added
var price= document.getElementById("price");
// Fill dropdown (quantity)
while (quantity.options.length) {
quantity.remove(0);
}
// fill by key
for( var quantity_key in arrayObjects ) {
var quantity_option = new Option(
quantity_key,
quantity_key
);
quantity.options.add(quantity_option);
}
// onChange-Listener
quantity.onchange = () => {
factor.value = arrayObjects[quantity.value];
// look for factor by key in arrayObjects
price.value = Math.round(
quantity.value *arrayObjects[quantity.value]
);
};
}
products();
<select id='quantity'></select>
KG
<input type='text' id='factor' readonly="readonly">
<input type='text' id='price' readonly="readonly">
in javascript, to get the selected element (value) of a select, use :
var e = document.getElementById("quantity");
var quantity= e.options[e.selectedIndex].text;

Adding and subtracting using dynamic variable names in JQuery/Javascript

I am working on developing an inventory checking form for my restaurant. The idea is that I can weigh for example a partially full bottle of Vodka (for example!) and from that weight the volume in milliliters will be automatically calculated based on the weight (adjuster) and density of the product.
The code is automatically generated with PHP. Here is an example, I choose which bottle of vodka and based on that choice I would like to display the amount in the span '1_liveWeight'. The problem I am having due to my limited experience is with this line of code:
var qty = (weight - adjuster) * density;
I would like it to function like this:
var qty = (weight - adjuster_!value selected from item_1!) * density!value selected from item_1!
The bits between the ! being where I would like to insert the value.
Below is an extract of the code generated in php.
HTML
<select id='item_1'>
<option value='3'>Smirnoff Vodka 1000ml</option>
<option value='4'>Absolute Vodka 750ml</option>
</select>
<input type='hidden' id='adjuster_3' value='140'>
<input type='hidden' id='density_3' value='0.96'>
<input type='hidden' id='adjuster_4' value='100'>
<input type='hidden' id='density_4' value='0.96'>
<input type='text' id ='weight_1' name ='weight'>
<span id='1_liveWeight'>0</span>
JQuery
$(document).ready(function(){
$("#item_1").change(function(){
var item = $('#item_1').val();
var adjuster3 = $('#adjuster_3').val();
var density3 = $('#density_3').val();
var adjuster4 = $('#adjuster_4').val();
var density4 = $('#density_4').val();
var weight = $('#weight_1').val();
var qty = (weight - adjuster)*density+item;
$("#1_liveWeight").html("<b>"+ qty +"</b>");
});
});
I hope I've explained my issue well enough! Thanks for the help,
DB
You need to assign the correct adjuster and density variable based on the item selection:
$(document).ready(function(){
$("#item_1").change(function(){
var item = $('#item_1').val();
var adjuster3 = $('#adjuster_3').val();
var density3 = $('#density_3').val();
var adjuster4 = $('#adjuster_4').val();
var density4 = $('#density_4').val();
var weight = $('#weight_1').val();
weight = Number(weight);
var adjuster, density;
if(item == 3){
adjuster = Number(adjuster3);
density = Number(density3);
}
else if(item == 4){
adjuster = Number(adjuster4);
density = Number(density4);
}
var qty = (weight - adjuster) * density;
$("#1_liveWeight").html("<b>"+ qty +"</b>");
});
});
I'd probably do it something more like this:
$(document).ready(function(){
var density = 0;
var adjuster = 0;
$("#item_1").change(function(){
recalculateWgt();
});
$("#weight_1").keyup(function(){
recalculateWgt();
});
recalculateWgt();
function recalculateWgt() {
var item = $('#item_1').val();
var adjuster = $('#adjuster_' + item).val();
var density = $('#density_' + item).val();
var weight = $('#weight_1').val();
var qty = (weight - adjuster)*density+item;
$("#1_liveWeight").html("<b>"+ qty +"</b>");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id='item_1'>
<option value='3'>Smirnoff Vodka 1000ml</option>
<option value='4'>Absolute Vodka 750ml</option>
</select>
<input type='hidden' id='adjuster_3' value='140'>
<input type='hidden' id='density_3' value='0.96'>
<input type='hidden' id='adjuster_4' value='100'>
<input type='hidden' id='density_4' value='0.96'>
<input type='text' id ='weight_1' name ='weight'>
<span id='1_liveWeight'>0</span>
You could use $("#weight_1").change() if you preferred to have the value update only when the quantity field loses focus.
I would say vodka really helped me a lot to understand but still i couldn't figure out - do you need details for just the selected product or for all when your dropdown changes? .Anyway here is something
$(document).ready(function(){
$("#item_1").change(function(){
var item = $('#item_1').val(); // may be 3 or 4 or whatever depends on choice
var adjuster = $('#adjuster_'+ item).val(); // dynamic selector
var density = $('#density_'+item).val();
var weight = $('#weight_'+item).val();
var qty = (weight - adjuster)*density; // density is constant at a given temp. for given liquid why were you chaging this? dilluting?
$("#"+item+"_liveWeight").html("<b>"+ qty +"</b>");
});
});
I ended up solving the problem by learning about eval()
It worked as intended:
eval("var chosenAdjuster = adjuster"+item);
eval("var chosenDensity = density"+item);
var qty = (weight - chosenAdjuster) * chosenDensity;

HTML / JQuery: Email an Entire Div/Table

I want to be able to email content such as a div that is in my webpage using the php mail function and possible putting it on the so called "Thank Your, Your Email Sent" page. However, I'm running into some issues. I am following this Email Div Content, Email div text content using PHP mail function, and GET entire div with its elements and send it with php mail function questions that has already been posted as a guide but it doesn't seem to be working for me. I want to send via email and show up on the "Thank Your, Your Email Sent" page within the message. Anything I'm doing wrong?
HTML Table that I want to send over is:
<div id="add_items_content" style="width:100%;">
<center>
<table id="add_item_here" style="width:98%;">
<tbody>
<tr><td>Item</td><td>Years</td><td>Quantity</td><td>Training Hours</td><td>Total Item Cost</td></tr>
</tbody>
</table>
</center>
<center>
<table id="add_totals_here" style="width:98%;">
<tbody>
<tr><td cospan="3"> </td><td> </td><td> </td></tr>
</tbody>
</table>
</center>
</div>
<script>
$(document).ready(function(){
$('table[id^=add_item_here]').hide();
$('table[id^=add_totals_here]').hide();
$('div[id^=office_submit]').hide();
$('div[id^=show_form]').hide();
//First obtaining indexes for each checkbox that is checked
$('input[name=item_chk]').change(function(){
var index = this.id.replace('item_chk','');
if($(this).is(':checked')){
AddNewItem(index);
}else{
RemoveItem(index);
}
CalculateTotals();
});
function AddNewItem(index){
// Get hidden variables to use for calculation and tables.
var item = $('#item_chk'+index).parent().text().trim();
var itemdescr = $('#itemdescr'+index).val();
var traininghrs = parseInt($('#traininghrs'+index).val());
var qty = parseInt($('#qty'+index).val());
var yrs = parseInt($('#yrs'+index).val());
var item_cost = 0;
// Calculating item cost for just that one checkbox
item_cost+=parseInt($('#servicefee'+index).val());
item_cost*=parseInt($('#yrs'+index).val());
item_cost+=parseInt($('#licensefee'+index).val());
item_cost*=parseInt($('#qty'+index).val());
var traininghrs = parseInt($('#traininghrs'+index).val());
//Display each item that is checked into a table
$('#add_item_here tr:last').after('<tr id="row_id'+index + '"><td style=\"width:35%;\">' + itemdescr +'</td><td style=\"width:15%;\" >' + yrs +'</td><td style=\"width:16%;\">' + qty +'</td><td style=\"width:18%;\">' + traininghrs + '</td><td style=\"width:16%;\">$'+ item_cost + '</td></tr>');
}
function RemoveItem(index){
$('table#add_item_here tr#row_id'+index).remove();
}
function CalculateTotals(){
var total_cost = 0;
var total_training = 0;
$('input:checkbox:checked').each(function(){
var index = this.id.replace('item_chk','');
var item_cost = 0;
// Calculating item cost for just that one checkbox
item_cost+=parseInt($('#servicefee'+index).val());
item_cost*=parseInt($('#yrs'+index).val());
item_cost+=parseInt($('#licensefee'+index).val());
item_cost*=parseInt($('#qty'+index).val());
var traininghrs = parseInt($('#traininghrs'+index).val());
total_cost +=item_cost;
total_training +=traininghrs;
});
if(total_cost > 0 || total_training > 0) {
$('#add_totals_here tr:last').children().remove();
$('#add_totals_here tr:last').after('<tr ><td colspan="3" style=\"width:66%;\">TOTALS:</td><td style=\"width:18%;\">' + total_training + '</td><td style=\"width:16%;\">$'+ total_cost + '</td></tr>');
$('#add_item_here').show();
$('#add_totals_here').show();
$('#office_submit').show();
}else{
$('table[id^=add_item_here]').hide();
$('table[id^=add_totals_here]').hide();
$('div[id^=office_submit]').hide();
}
}
$("input[name='office_submit']").click(function () {
$('#show_form').css('display', ($(this).val() === 'Yes') ? 'block':'none');
});
// Quantity change, if someone changes the quantity
$('select[name=qty]').change(function(){
var index = this.id.replace('qty','');
if($("#item_chk"+index).is(':checked')){
RemoveItem(index);
AddNewItem(index);
CalculateTotals();
}
});
// Years change, if someone changes the years
$('select[name=yrs]').change(function(){
var index = this.id.replace('yrs','');
if($("#item_chk"+index).is(':checked')){
RemoveItem(index);
AddNewItem(index);
CalculateTotals();
}
});
})
</script>
Trial Number 1; So far I have tried:
<script>
function mail_content() {
var tablesContent = document.getElementById("add_items_content").innerHTML;
$.post('send_form.email.php',{content:tablecontent},function(data) {
});
}
</script>
Using script I have added to the send_form_email.php:
<?php
$txt = $_POST['content'];
mail($to,$subject,$message,$txt,$headers);
mail($from,$subject2,$message2,$txt,$headers2);
?>
Trial Number 2: I even tried storing it into a hidden field:
<input name="data" id="data" type="hidden" value=""></input>
<script type="text/javascript">
$(document).ready(function(){
$("#price_quote").submit(function() { //notice submit event
$("#my_hidden_field").val($("#add_items_content").html()); //notice html function instead of text();
});
});
</script>
And then the send_form_email.php I put it in that message see if it even shows up.
$txt = $_POST['data'];
$message = "Content: ".$txt."\n";
mail($to,$subject,$message,$txt,$headers);
mail($from,$subject2,$message2,$txt,$headers2);
Trial Number 3: Even tried Ajax
<script>
function mail_content(){
var html = $('#add_items_content').html();
$.ajax(function{
type="POST",
url:"send_form_email.php",
data:"data="+html,
success:function(response){
$('#add_items_content').show().html("email sent");
}
});
}
</script>
What am I missing or doing wrong? Why doesn't the div / tables show up or display?
You really should check your JS console for errors:
var tablesContent = document.getElementById("add_items_content").innerHTML;
^---note the "sC"
$.post('send_form.email.php',{content:tablecontent},function(data) {
^--note the c
JS vars are case sensitive, and will NOT magically correct typos for you.
And then there's this:
<input name="data" id="data" type="hidden" value=""></input>
^---id 'data'
$("#my_hidden_field").val($("#add_items_content").html());
^--- completely DIFFERENT ID

Total function for multiple input-steppers

I am trying to understand how write a total function to call on multiple input-steppers that I used from a library. I did read the documentation of the library on how to call things. Now I can increment & decrement 1 stepper and multiply by a variable, and display in total field. I can't figure out how to change the total function so it can be used on all steppers and displayed in 1 total field. Do I need if else or a loop? I'm not sure how to start. Also not sure how to add library here?
$(document).ready(function(){
$(function () {
// Document ready
$('.input-stepper').inputStepper();
});
});
var value1 = 0.95;
var value2 = 4.00;
var value3 = 2.00;
// These are to call inputs
$('#amount1').on('increase', function (e, amount, plugin) {
calculate();
});
$('#amount1').on('decrease', function (e, amount, plugin) {
});
$('#amount2').on('increase', function (e, amount, plugin) {
});
$('#amount2').on('decrease', function (e, amount, plugin) {
});
$('#amount3').on('increase', function (e, amount, plugin) {
});
$('#amount3').on('decrease', function (e, amount, plugin) {
});
// these are to call stepper buttons
$('[data-input-stepper-increase] ').click(function(){
});
$('[data-input-stepper-decrease]').click(function(){
});
function calculate(){
var total = 0;
var quantity = parseInt($('#amount1 ').val());
total = value1 * quantity;
console.log(total);
$('#TotalField').val(total.toFixed(2));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3>$0.95 value</h3>
<button data-input-stepper-decrease>-</button>
<input id="amount1"type="text" value="0">
<button data-input-stepper-increase >+</button>
<h3>$4.00 value</h3>
<button data-input-stepper-decrease>-</button>
<input id="amount2"type="text" value="0">
<button data-input-stepper-increase>+</button>
<h3>$2.00 value</h3>
<button data-input-stepper-decrease>-</button>
<input id="amount3"type="text" value="0">
<button data-input-stepper-increase>+</button>
<label>Total</label><input type="text"
class="" id="TotalField" name="TotalField" />
Here is link to library https://github.com/AanZee/input-stepper
link to codpen I am working on
http://codepen.io/Ongomobile/pen/kXogvZ?editors=1111
About the binding, both increase and decrease could be bound in one go:
$('[id^=amount]').on('increase decrease', calculate);
Instead of '[id^=amount]', you could also use '#amount1,#amount2, etc', but better yet would be to have a common class
For easier summarizing the values should be in a collection, such as var values = [0.95, 4.00, 2.00]; (although you could also put them in (data) properties on the elements)
Then, if boxes is the jQuery variable of the inputs, you could summarize with:
var total = 0;
boxes.each(function(ind,box){ total+= values[ind] * $(box).val();});
Finalizing, the whole would look like:
var boxes = $('[id^=amount]').on('increase decrease', calculate); //bind the elements and assing to the boxes variable in one go
var values = [0.95, 4.00, 2.00];
function calculate(){
var total = 0;
boxes.each(function(ind,box){ total+= values[ind] * $(box).val();});
console.log(total);
$('#TotalField').val(total.toFixed(2));
}
codepen
I believe the below solution is what you're looking for, judging from your current code:
var value1 = 0.95;
var value2 = 4.00;
var value3 = 2.00;
// these are to call stepper buttons
$('[data-input-stepper-increase] ').click(function(){
calculate();
});
$('[data-input-stepper-decrease]').click(function(){
calculate();
});
function calculate(){
var total = 0,
quantity1 = parseInt($('#amount1 ').val()),
quantity2 = parseInt($('#amount2').val()),
quantity3 = parseInt($('#amount3 ').val());
total = (value1 * quantity1)+(value2 * quantity2)+(value3 * quantity3);
$('#TotalField').val(total.toFixed(2));
}

Categories

Resources