i want to make money value have commas in it, i know this question is already ask, but i kinda new to javascript or jquery in general, my problem is i dont know how to apply some of those code with mine
This is my jQuery code
<script>
$(function sum() {
console.log($('.calc'))
var sum = 0.0;
$('.calc').each(function() {
sum += parseInt($(this).text());
});
$("#subTotal").val(sum);
})();
function calculateSubTotal() {
var subtotal = $("#subTotal").val();
$("#subTotalDiscount").val(subtotal - (Math.round(($("#inputDiscount").val() / 100) * subtotal)));
var subtotal_discount = parseInt($("#subTotalDiscount").val());
$("#subTotalTax").val(Math.round(($("#inputTax").val() / 100) * subtotal_discount));
var subtotal_tax = parseInt($("#subTotalTax").val());
var pph = $("#inputpph").val();
$("#SubTotalpph").val(Math.round(parseInt($("#inputpph").val()*subtotal_discount)));
var subtotal_pph = parseInt($("#SubTotalpph").val());
var grandtotal = subtotal_discount + subtotal_tax + subtotal_pph;
$("#grandTotal").val(grandtotal);
}
</script>
This is my table code
<div class="row mt-3">
<div class="col-lg">
<div class="table-fix-head">
<table class="table table-fixed table-bordered table-hover" style="width:100%;" id="tebal">
<thead>
<tr>
<th scope="col">DKM No </th>
<th scope="col">Kode Produksi </th>
<th scope="col">Kode Barang </th>
<th scope="col">Deskripsi </th>
<th scope="col">Jumlah/Quantity </th>
<th scope="col">Unit </th>
<th scope="col">Unit Price </th>
<th scope="col">Sub Total </th>
</tr>
</thead>
<tbody>
<?php $i = 1;
foreach ($query as $kiki) : ?>
<tr class="table-row">
<td><?php echo $i++; ?></td>
<td><?php echo $kiki["kodeprod"]; ?></td>
<td><?php echo $kiki["kodebarang_op"]; ?></td>
<td><?php echo $kiki["catatan"]; ?></td>
<td><?php echo $kiki["qty_op"]; ?></td>
<td><?php echo $kiki["unit_op"]; ?></td>
<td><?php echo $kiki["price"]; ?></td>
<td class="calc"><?php echo $kiki["qty_op"]*$kiki["price"]; ?></td>
</tr>
<?php endforeach;?>
</tbody>
</table>
</div>
</div>
</div>
what i want is that the number in my table and my output value have commas like '122.000.000'
the table preview : https://i.imgur.com/akbfJku.png
form :
<div class="form-group">
<div class="row">
<div class="col-lg-3">
<label for="total" class="label-control" id="labelsubtotal">Total : </label>
</div>
<div class="col-lg-9">
<input type="number" value="" style="text-align: right;" class="form-control money" id="grandTotal" name="grandTotal" disabled>
</div>
</div>
</div>
By doing a javascript function
function commasNumber(yourMoneyValue) {
return yourMoneyValue.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
or by using your example
function commasNumber() {
var subtotal = $("#subTotal").val();
var valueWithCommas = subtotal.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
$("#subTotal").val(valueWithCommas);
}
By modifying t hj's answer, you could replace and also remove the commas for the purpose of calculating the prices :
<script>
$(document).ready(function () {
console.log($('.calc'))
var sum = 0.0;
$('.calc').each(function () {
sum += parseInt($(this).text());
});
$("#subTotal").val(addCommas(sum));
});
function calculateSubTotal() {
var subtotal = removeCommas($("#subTotal").val());
$("#subTotalDiscount").val(addCommas(+subtotal - (Math.round(($("#inputDiscount").val() / 100) * subtotal))));
var subtotal_discount = parseInt(removeCommas($("#subTotalDiscount").val()));
$("#subTotalTax").val(addCommas(Math.round(($("#inputTax").val() / 100) * subtotal_discount)));
var subtotal_tax = parseInt(removeCommas($("#subTotalTax").val()));
var pph = $("#inputpph").val();
$("#SubTotalpph").val(addCommas(Math.round(parseInt(pph * subtotal_discount))));
var subtotal_pph = parseInt(removeCommas($("#SubTotalpph").val()));
var grandtotal = subtotal_discount + subtotal_tax + subtotal_pph;
$("#grandTotal").val(grandtotal);
}
function addCommas(moneyValue) {
return moneyValue.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");
}
function removeCommas(moneyValue) {
return moneyValue.toString().replace(".", "");
}
</script>
You can use javascript like #t-hj post or if you want to use PHP, here's some example
<?php echo number_format($kiki["price"], 0, '', ',') ?>
Read more about PHP number_format
Related
in the view file "(V_tampil_rekomendasi)", I made an input text containing the latitude and longitude values of a function to check the current location.
In the results, I sent it to the file controller and it worked. I checked using the var_dump function.
But when I send it (latitude and longitude) to the model file (M_Metode).The values of latitude and longitude were missing.
And the results that will be displayed on V_display_ recommendation are missing or nothing to display.
This my view file :
<button class="btn btn-primary" onclick="getLocation()">Cek Lokasi Anda</button></p>
<form action="<?php echo base_url().'metode/index'; ?>" method="post">
<div class="row">
<div class="col">
<p class="font-weight-bold">LATITUDE :</p>
<input class="form-control" type = "text" id = "out_latitude" name="latitude_awal" placeholder="Latitude" readonly/>
</div>
<div class="col">
<p class="font-weight-bold">LONGITUDE :</p>
<input class="form-control" type = "text" id = "out_longitude" name="longitude_awal" placeholder="Longitude" readonly/>
</div>
</div>
<br>
<input class="btn btn-primary" type="submit" value="Cari Fotografer">
</form>
<table class="table table-bordered" style="margin:20px auto;" border="1">
<tr>
<thead class="thead-dark">
<th>No</th>
<th>Nama</th>
<th>Alamat</th>
<th>Kamera</th>
<th>Spesifikasi Foto</th>
<th>Jarak</th>
</thead>
</tr>
<?php
$no = 1;
foreach($tb_fotografer as $fg)
{
?>
<tr>
<td><?php echo $no++ ?></td>
<td><?php echo $fg['nama'] ?></td>
<td><?php echo $fg['alamat'] ?></td>
<td><?php echo $fg['kamera'] ?></td>
<td><?php echo $fg['keahlian_foto'] ?></td>
<td><?php echo $fg['distance']?> Km </td>
</tr>
<?php } ?>
</table>
My Javascript to check the current location (in View file) :
<script>
var view_lat = document.getElementById("tampilkan_lat");
var view_long = document.getElementById("tampilkan_long");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
view.innerHTML = "Yah browsernya ngga support Geolocation bro!";
}
}
function showPosition(position) {
var var_latitude = position.coords.latitude;
document.getElementById("out_latitude").value = var_latitude ;
var var_longitude = position.coords.longitude;
document.getElementById("out_longitude").value = var_longitude ;
}
</script>
This my Controller :
function index()
{
$latitude = $this->input->post('latitude_awal');
$longitude = $this->input->post('longitude_awal');
$data_latlong = array(
'latitude_awal' => $latitude,
'longitude_awal' => $longitude);
$data_fotografer= $this->m_metode->tampil_data_fotografer($data_latlong);
$this->load->view('public/pencari/v_tampil_rekomendasi',['tb_fotografer' => $data_fotografer]);
}
This my model :
function tampil_data_fotografer($data_latlong)
{
$latFrom = deg2rad((float)('latitude_awal'));
var_dump($latFrom);
$lonFrom = deg2rad((float)('longitude_awal'));
var_dump($lonFrom);
$data_fg = $this->db->query("SELECT fotografer_id, nama, alamat, kamera, keahlian_foto, latitude, longitude FROM tb_fotografer");
$out = [];
{
foreach($data_fg->result_array() as $row)
{
$keahlianfoto = $row['keahlian_foto'];
$latTo = deg2rad((float)$row['latitude']);
$lonTo = deg2rad((float)$row['longitude']);
$latDelta = $latTo - $latFrom;
$lonDelta = $lonTo - $lonFrom;
$distance = (2 * asin(sqrt(pow(sin($latDelta / 2), 2) + cos($latTo) * cos($latFrom) * pow(sin($lonDelta / 2), 2)))) * 6371;
if ($distance <=1)
{
$out[] = array_merge($row, ['distance' => $distance]);
}
}
}
return $out;
}
Anyone kno what the problem ? Help me please, thanks
The following code (in your model):
$latFrom = deg2rad((float)('latitude_awal')); // (float)('latitude_awal') = 0
var_dump($latFrom);
$lonFrom = deg2rad((float)('longitude_awal')); // (float)('longitude_awal') = 0
var_dump($lonFrom);
should be like this:
$latFrom = deg2rad((float) $data_latlong['latitude_awal']);
$lonFrom = deg2rad((float) $data_latlong['longitude_awal']);
i am loading a page for my pending orders in view and displaying the data in a table i am calculating line total through javascript and it is going well but when i try to show in the page there is error in getting the element by its id and is the error is: Cannot set property 'innerHTML' of null
<div class="ziehharmonika">
<?php if( count($pending_orders) ): ?>
<?php foreach ($pending_orders as $info): ?>
<h3 id="header3" style="background-color: #00bad3; color:white;"
onclick="get_line_total(<?php print_r($info['id']);?>);"><span
style="color: black;">order# </span> <?php print_r($info['id']);?>
Status: </span> <span id="status<?php print_r($info['id']);?>"><?php
print_r($info['status']);?></span></h3>
<div class="w3_agile_recipe-grid">
<section>
<table cellpadding="0" cellspacing="0" class="ordertable"
id="ordertable<?php print_r($info['id']);?>">
<tr>
<th>Sr_No</th> <!-- Dummy cell for the row number and row commands
<th>Id</th>
<th>item_Name</th>
<th>price</th>
<th>company</th>
<th>quantity</th>
<th>line_total</th>
</tr>
<?php if( count($info['porders']) ): ?>
<?php
$row_count = 1;
foreach ($info['porders']as $order_info){ ?>
<tr>
<td><?php echo $row_count; ?></td> <!-- Don't remove this column
as it's needed for the row commands -->
<td class="ord_id"><?php print_r($order_info['id']);?></td>
<td><?php print_r($order_info['name']);?></td>
<td class="ord_price"><?php print_r($order_info['price']);?></td>
<td><?php print_r($order_info['company']);?></td>
<td class="ord_qty"><?php print_r($order_info['quantity']);?></td>
<td class="line_total"></td>
</tr>
<?php $row_count++; }?>
</table>
<?php else: ?>
<?php endif;?>
<div><span>Total Amount</span><p id="tota<?php
print_r($order_info['id']);?>"></p></div>
<div class="clearfix"></div>
</section>
</div>
</div>
my javascript is;
var get_line_total = function(id){
var table = document.getElementById('ordertable'+id);
ord_price=0;
ord_qty=0;
linetotal=0;
for (var r = 1, n = table.rows.length; r < n; r++) {
ord_price = parseInt(table.rows[r].cells[3].innerHTML);
ord_qty = parseInt(table.rows[r].cells[5].innerHTML);
linetotal= ord_price * ord_qty;
table.rows[r].cells[6].innerHTML = linetotal;
}
ord_total=0;
for (var r = 1, n = table.rows.length; r < n; r++) {
ord_total = ord_total + parseInt(table.rows[r].cells[6].innerHTML);
}
// this line is giving above said error
document.getElementById('tota'+id).innerHTML = ord_total;
}
can any body help me to correct this code and get rid of the error
I am doing calculation in the third input field based on the value filled in the two input field. And here I have multiple row. Each row calculation should be done separately so i am using each function. But the calculation is not working.
I am new in Jquery so where code is getting wrong??
<table>
<tr>
<th><?= __('Quantity Offered')?></th>
<th><?= __('Offer Price')?></th>
<th><?= __('Total Offer Price')?></th>
</tr>
<tr class="productNRow">
<td><?php echo $this->Form->input("supplier_offer_products.0.qty_offered",['id'=>'qtyOffered']);?></td>
<td><?php echo $this->Form->input("supplier_offer_products.0.offer_price",['id'=>'priceOffered']);?></td>
</tr>
<tr class="productNRow">
<td><?php echo $this->Form->input("supplier_offer_products.1.qty_offered",['id'=>'qtyOffered']);?></td>
<td><?php echo $this->Form->input("supplier_offer_products.1.offer_price",['id'=>'priceOffered']);?></td>
</tr>
</table>
<script>
$(document).ready(function(){
$(".productNRow").each(function(){
var sentRec = $(this);
var total;
$(this).find("#qtyOffered").on('change', function () {
var qty = $(sentRec).find("#qtyOffered").val();
var offer = $(sentRec).find("#priceOffered").val();
var total = qty * offer;
$('#totalOrder').val(total);
});
});
});
You cannot have multiple IDs. Use classes and add the missing #totalOrder elements.
The jQuery and PHP than could look like this:
jQuery(function( $ ) {
$(".productNRow").each(function() {
var $row = $(this);
var $qty = $row.find(".qtyOffered"); // use classes! (see PHP too)
var $prc = $row.find(".priceOffered");
var $tot = $row.find(".totalOrder");
$qty.on('input', function() {
var qty = $(this).val();
var offer = $prc.val();
var total = qty * offer;
$tot.val(total);
});
});
});
<table>
<tr>
<th>Quantity Offered</th>
<th>Offer Price</th>
<th>Total Offer Price</th>
</tr>
<tr class="productNRow">
<td>
<?php echo $this->Form->input("supplier_offer_products.0.qty_offered",['class'=>'qtyOffered']);?>
</td>
<td>
<?php echo $this->Form->input("supplier_offer_products.0.offer_price",['class'=>'priceOffered']);?>
</td>
<td>
<input class="totalOrder">
</td>
</tr>
<tr class="productNRow">
<td>
<?php echo $this->Form->input("supplier_offer_products.1.qty_offered",['class'=>'qtyOffered']);?>
</td>
<td>
<?php echo $this->Form->input("supplier_offer_products.1.offer_price",['class'=>'priceOffered']);?>
</td>
<td>
<input class="totalOrder">
</td>
</tr>
</table>
or going the other way around (input→parent→inputs) without using the .each() method
jQuery(function( $ ) {
$(".qtyOffered").on('input', function() {
var $row = $(this).closest(".productNRow");
var $prc = $row.find(".priceOffered");
var $tot = $row.find(".totalOrder");
var qty = $(this).val();
var offer = $prc.val();
var total = qty * offer;
$tot.val(total);
});
});
I am working with MDL Checkbox where i need to delete all values at once. As i did some research and looks like old method is deprecated : Deprecations for MDL Data Table Checkbox and mdl-data-table--selectable can't be used anymore.
HTML Code:
<div class="load_customer">
<table class="mdl-data-table mdl-js-data-table mdl-shadow--2dp mdl-cell mdl-cell--12-col mdl-cell--12-col-tablet mdl-cell--7-col-phone">
<thead>
<tr>
<th>
<label class="mdl-checkbox mdl-js-checkbox mdl-js-ripple-effect mdl-data-table__select" id="table-header" for="table-input">
<input type="checkbox" id="table-input" class="mdl-checkbox__input" />
</label>
</th>
<th>Sr. No</th>
<th>Name</th>
<th>Gender</th>
<th>Date of Birth</th>
<th>Anniversary</th>
<th>Address</th>
<th>Phone</th>
</tr>
</thead>
<tbody>
<?php
$i=1;
$select = $pdo->query("SELECT * FROM `accounts` ORDER BY `id` DESC");
while($fetch = $select->fetch()){
?>
<tr>
<td>
<label class="mdl-checkbox child_checkbox mdl-js-checkbox mdl-js-ripple-effect mdl-data-table__select" data="<?php echo $fetch['id'];?>" for="row[<?php echo $i;?>]">
<input type="checkbox" id="row[<?php echo $i;?>]" class="mdl-checkbox__input" />
</label>
</td>
<td><?php echo $i;?></td>
<td><?php echo $fetch['name'];?> </td>
<td><?php echo $fetch['gender'];?></td>
<td><?php echo $fetch['dob'];?></td>
<td><?php echo $fetch['anniversary'];?></td>
<td><?php echo $fetch['address'];?></td>
<td><?php echo $fetch['phone'];?></td>
</tr>
<?php
$i++;
}
?>
</tbody>
</table>
</div>
So after adding it manually it works fine until i load table with ajax. Then it all stops working. I am able to check main checkbox #table-header, but function which checks all checkboxes (MaterialCheckbox.check()) does not works anymore. I checked console & there are no errors in console.
Javascript Code
var arr = [];
$(document).on("click","#table-header input",function() {
var all_elements = document.querySelectorAll('.child_checkbox');
for(var i=0, n=all_elements.length; i<n; i++){
var element = all_elements[i];
if($('#table-header input').is(":checked")) {
element.MaterialCheckbox.check();
var ids = element.getAttribute("data");
arr.push(ids);
}
else {
element.MaterialCheckbox.uncheck();
var removeItem = element.getAttribute("data");
arr = $.grep(arr, function(value) {
return value != removeItem;
});
}
}
});
I am using componentHandler.upgradeAllRegistered() and Checkbox is working fine, but it does not loop through all checkboxes.
$.post("load_customer.php",function(data){
$(".load_customer").html(data);
componentHandler.upgradeAllRegistered();
});
Please help me with this.Thanks.
I have this JavaScript code, it works well, but when I tried to customize some math operations based on $id_math, it reads only the first row of the array inside the while loop, so calculate all the rows using the same $id_math, What changes do I need to do in my code, to get individual $id_math for every single row and perform the corresponding operation?.
$id_math is a php variable I use to store the value I got from my database.
example: $id_math = 11, $operation_name = addition.
Here is my example.
Script
$(function(){
CalculateTotal();
// Adding the change events for the Price and
// quantity fields only..
// Changing the total should not affect anything
$('.quantity , .price').on('change', function() {
UpdateTotals(this);
});
});
function UpdateTotals(elem) {
// This will give the tr of the Element Which was changed
//in my code I have it like this
var abc=<?php echo id_math ?>;
var $container = $(elem).parent().parent();
var quantity = $container.find('.quantity').val();
var price = $container.find('.price').val();
var subtotal = parseFloat(quantity) + parseFloat(price);
var subtotalmultiplication = parseFloat(quantity) * parseFloat(price);
var subtotaldivision = parseFloat(quantity) / parseFloat(price);
switch (abc) {
case 12:
$container.find('.subtotal').text(subtotal.toFixed(2));
$container.find('.txtresult').val(subtotal.toFixed(2));
break;
case 11:
$container.find('.subtotal').text(subtotalmultiplication.toFixed(2));
$container.find('.txtresult').val(subtotalmultiplication.toFixed(2));
break;
case 13:
$container.find('.subtotal').text(subtotaldivision.toFixed(2));
$container.find('.txtresult').val(subtotaldivision.toFixed(2));
break;
}
//document.getElementById("txtresult").value = subtotal.toFixed(2);
}
function CalculateTotal(){
// This will Itearate thru the subtotals and
// claculate the grandTotal and Quantity here
var lineTotals = $('.subtotal');
var quantityTotal = $('.quantity');
var grandTotal = 0.0;
var totalQuantity = 0;
$.each(lineTotals, function(i){
grandTotal += parseFloat($(lineTotals[i]).text()) ;
totalQuantity += parseFloat($(quantityTotal[i]).val())
});
$('.totalquantity').text(totalQuantity);
$('.grandtotal').text(parseFloat(grandTotal ).toFixed(2) );
}
php code
<table id="tabla-registros" class="table table-striped table-bordered bootstrap-datatable datatable responsive">
<thead>
<tr>
<th>Nº Reg</th>
<th>Fecha</th>
<th>Nombre Completo del Paciente</th>
<th>Clave para la Descarga</th>
<th>Estado del Registro</th>
<th>Acciones</th>
</tr>
</thead>
<tbody>
<?php
$numrows = mysql_num_rows($list_results);
if($numrows > 0){
while($row=mysql_fetch_array($list_results)){
$patient_name= utf8_encode($row['nombrepaciente']);
$keyword= $row['llave'];
$url_result= $row['resultado'];
$comments= $row['observaciones'];
$status_result= $row['nombre_estado'];
$date_result= $row['fecha'];
$id_status= $row['idestado'];
$id_resultado= $row['idresultados'];
$id_math = $row['idmath'];
?>
<tr>
<td><?php echo $id_resultado;?></td>
<td><?php echo $date_result;?></td>
<td><?php echo $patient_name;?></td>
<td><?php echo $keyword;?></td>
<?php switch($id_status){
case '3':?>
<td><span class="label-success label label-default"><?php echo $status_result; ?></span></td>
<?php break; ?>
<?php case '1':?>
<td> <span class="label-warning label label-default"><?php echo $status_result; ?></span></td>
<?php break;?>
<?php case '2':?>
<td> <span class="label-default label label-danger"><?php echo $status_result; ?></span></td>
<?php break; }?>
<!--This is the block of the code where I need help because the javascript code only reads the first row of the while loop to perform the operation, but the second row has another id_math to calculate other operations -->
<table>
<tr>
<th width=200px>Description</th>
<th width=60px>DATA1</th>
<th width=60px>DATA2</th>
<th width=60px>Total</th>
</tr>
<tr>
<td width=200px>CALCULATE</td>
<td width=60px><input type="text" value="15.99" class="price" /></td>
<td width=60px><input type="text" value="1" class="quantity" /></td>
<td width=60px><input type="text" value="" name="txtresult" id= "txtresult" class="txtresult" /></td>
</tr>
</table>