Switch case (JavaScript) inside a while loop (PHP) - javascript

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>

Related

How to add commas in value

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

Unable to store particular target values in jQuery

$(document).ready(e => {
$(".test").click(e => {
textvalue = displayData(e);
console.log(textvalue); //prints the array
});
});
function displayData(e) {
let i = 0;
const td = $("#tbody tr td");
let textvalues = [];
for (const value of td) {
if (value.dataset.name == e.target.dataset.name) {
textvalues[i++] = value.textContent;
}
}
return textvalues;
}
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<table>
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>Gender</th>
<th>Email</th>
<th>Contact</th>
<th>Department</th>
<th>Edit</th>
</tr>
</thead>
<tbody id="tbody">
<tr>
<td>DummyName</td>
<td>20</td>
<td>Female</td>
<td>DummyEmail</td>
<td>DummyContact</td>
<td>DummyDepartment</td>
<td class="test">Click</td>
</tr>
<tr>
<td>DummyName2</td>
<td>22</td>
<td>Female</td>
<td>DummyEmail2</td>
<td>DummyContact2</td>
<td>DummyDepartment2</td>
<td class="test">Click</td>
</tr>
</tbody>
</table>
</body>
</html>
I'm using jQuery to update onscreen values in a form. Complete beginner at this.
$(document).ready(e =>{
$(".btnedit").click(e =>{
textvalues = displayData(e);
let sname = $("input[name*='name_type");
let sage = $("input[name*='age_type");
let sgender = $("input[name*='gender_type");
let semail = $("input[name*='email_type");
let scontact = $("input[name*='contact_type");
let sdept = $("input[name*='dept_type");
sname.val(textvalues[0]);
sage.val(textvalues[1]);
sgender.val(textvalues[2]);
semail.val(textvalues[3]);
scontact.val(textvalues[4]);
sdept.val(textvalues[5]);
});
});
function displayData(e){
let i = 0;
const td = $("#tbody tr td");
let textvalues = [];
for(const value of td){
if(value.dataset.name == e.target.dataset.name)
{
//console.log(value);
textvalues[i++] = value.textContent;
}
}
return textvalues;
}
I need to get the data stored in a table onto the inputs of the form, in order for the user to update it further. The user clicks on a record to edit it(which is displayed on the page).
The record values are stored in the array textvalues. Problem is the entire table values get stored in the array instead of just the single record.
In value.dataset.name, name is a column from the table which I'm using as the primary key (I know it's wrong, but just going with it for now).
Edit: Original table code:
while($row = mysqli_fetch_assoc($result))
{
?>
<tr>
<td data-name = "<?php echo $row['name']; ?>"><?php echo $row['name'];?></td>
<td data-name = "<?php echo $row['name']; ?>"><?php echo $row['age'];?></td>
<td data-name = "<?php echo $row['name']; ?>"><?php echo $row['gender'];?></td>
<td data-name = "<?php echo $row['name']; ?>"><?php echo $row['email'];?></td>
<td data-name = "<?php echo $row['name']; ?>"><?php echo $row['contact'];?></td>
<td data-name = "<?php echo $row['name']; ?>"><?php echo $row['department'];?></td>
<td data-name = "<?php echo $row['name']; ?>"><i class="fas fa-edit btnedit"></i></td>
</tr>
<?php
}
Your code works fine except one little thing: all your input selectors lack closing quote and bracket, e.g. this is wrong (jQuery 3.3.1 throws error):
let sname = $("input[name*='name_type");
But this is right:
let sname = $("input[name*='name_type']");
Otherwise, it works just fine (well, certain optimizations can be done, that's true, but still it works as is) -- if I have guessed your HTML structure correctly, see example below. (Disclaimer: this is by no means a good piece of code with best pracrices etc. This is just a reproduction of original task with minimal fix to make it work.)
$(document).ready(e => {
$(".btnedit").click(e => {
textvalues = displayData(e);
let sname = $("input[name*='name_type']");
let sage = $("input[name*='age_type']");
let sgender = $("input[name*='gender_type']");
sname.val(textvalues[0]);
sage.val(textvalues[1]);
sgender.val(textvalues[2]);
});
});
function displayData(e) {
let i = 0;
const td = $("#tbody tr td");
let textvalues = [];
for (const value of td) {
if (value.dataset.name == e.target.dataset.name) {
textvalues[i++] = value.textContent;
}
}
return textvalues;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tbody id="tbody">
<tr>
<td data-name="1">a1</td>
<td data-name="1">b1</td>
<td data-name="1">c1</td>
<td><button class="btnedit" data-name="1">edit</button></td>
</tr>
<tr>
<td data-name="2">a2</td>
<td data-name="2">b2</td>
<td data-name="2">c2</td>
<td><button class="btnedit" data-name="2">edit</button></td>
</tr>
</tbody>
</table>
Type: <input type="text" name="name_type" /><br />
Age: <input type="text" name="age_type" /><br />
Gender: <input type="text" name="gender_type" />
Possible reason of could be this: data-name is invalid everywhere in your table. If that's not the case, please share some more code. Minimal yet complete example would be great.
Update: in your example HTML I see no data-name attributes at all, and clickable element also does not have it. So, your selector $('#tbody th td') matches all TDs, and that's why you see whole table in output.
So, look at the example above and do the same with data-name: every <td> and the button on one row have the same value in that attribute.

How to get a javascript function working inside a php table?

I am trying to get the Multiply function to run and multiply the Order Quantity times the item price. I cannot get the function to run inside the PHP loop using the oninput attribute.
<script type="text/javascript">
function Multiply() {
var myBox1 = document.getElementById('editedvalues[]').value;
var myBox2 = document.getElementById('price').value;
var result = document.getElementById('result');
var myResult = myBox1 * myBox2;
result.value = myResult;
}
</script>
<?php
$sql = "SELECT item_price.item_id,
item_price.ITEM_NAME,
suggested_qty,
Price_item
FROM item_price
JOIN suggested_item ON item_price.ITEM_NAME = suggested_item.ITEM_NAME";
$result = $conn->query($sql);
?>
form action="#" method="post">
<tr>
<th> ID</th>
<th>Item Name</th>
<th>Suggested Quantity</th>
<th>Price</th>
<th>OrderQuanity</th>
<th>Total Cost</th>
</tr>
<?php
while ($row = $result->fetch_assoc())
{
echo "<tr>";
echo "<td>{$row['item_id']}</td>";
echo "<td>{$row['ITEM_NAME']}</td>";
echo "<td>{$row['suggested_qty']}</td>";
echo "<td>{$row['Price_item']}</td>";
echo "<td><input type='text' name='editedvalues[]' value='{$row['suggested_qty']}' oninput='Multiply()' /></td>";
echo "<td><input name='result' /></td>";
echo "</tr>";
}
?>
You're using the document.getElementById function to refer to elements, but in addition to the fact that there are multiple inputs that this function can run on, your inputs don't even have an ID.
To make sure this function works on the input in question, you'll need to look at the target of the event instead of ignoring it. As well, you should use proper event binding instead of inline oninput attributes.
You also weren't using a table element, and you should really break out of PHP for huge blocks of HTML code.
This would be much easier using some framework like jQuery, but this should work.
var nodes = document.getElementsByClassName("qtyinput");
for (var i = 0; i < nodes.length; i++) {
nodes[i].addEventListener('input', multiply, false);
}
function multiply(e) {
var qty = e.target.value;
var price = e.target.parentNode.parentNode.getElementsByClassName("pricetd")[0].textContent;
var result = e.target.parentNode.parentNode.getElementsByClassName("resultinput")[0];
var myResult = qty * price;
result.value = myResult;
}
<?php
$sql = "SELECT item_price.item_id,
item_price.ITEM_NAME,
suggested_qty,
Price_item
FROM item_price
JOIN suggested_item ON item_price.ITEM_NAME = suggested_item.ITEM_NAME";
$result = $conn->query($sql);
?>
<form action="#" method="post">
<table>
<tr>
<th> ID</th>
<th>Item Name</th>
<th>Suggested Quantity</th>
<th>Price</th>
<th>OrderQuanity</th>
<th>Total Cost</th>
</tr>
<!-- test data for snippet -->
<tr>
<td>111</td>
<td>Test item</td>
<td>4</td>
<td class="pricetd">40</td>
<td>
<input type="text" name="editedvalues[]" class="qtyinput" value="4" />
</td>
<td><input name='result' class="resultinput" /></td>
</tr>
<?php while ($row = $result->fetch_assoc()) :?>
<tr>
<td><?=$row["item_id"]?></td>
<td><?=$row["ITEM_NAME"]?></td>
<td><?=$row["suggested_qty"]?></td>
<td class="pricetd"><?=$row["Price_item"]?></td>
<td>
<input type="text" name="editedvalues[]" class="qtyinput" value="<?=$row["suggested_qty"]?>" />
</td>
<td><input name='result' class="resultinput" /></td>
</tr>
<?php endwhile?>
</table>
<form>

calculation of two input field into third input field having multiple table rows in jquery

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);
});
});

Display All Table Rows that are Checked

I have a multiple column table with one column being checkboxes. If you check a checkbox then press the "Checkout" button, it will take the specified rows and display them in the body of an email.
I originally bring in the top 100 rows to keep the info light for the user. I also have a search functionality where the user can search for specific rows. While you can maneuver throughout different searches and still keep all of the checkboxes checked with session storage, when you hit "Checkout" it only displays the table rows that are checked and currently visible on the page. So, if I searched for a table row and checked it, but then went back to the original top 100 rows by clicking home, then that row would not display on the email.
How can I fix this and show ALL rows that have been checked, whether they are visible on the page or not?
HTML:
<section id="checkout-btn">
<button id="checkout" name="order" onclick="sendMail(); return false">Checkout</button>
</section>
<br>
<table id="merchTable" cellspacing="5" class="sortable">
<thead>
<tr class="ui-widget-header">
<th class="sorttable_nosort"></th>
<th class="sorttable_nosort">Loc</th>
<th class="merchRow">Report Code</th>
<th class="merchRow">SKU</th>
<th class="merchRow">Special ID</th>
<th class="merchRow">Description</th>
<th class="merchRow">Quantity</th>
<th class="sorttable_nosort">Unit</th>
<th style="display: none;" class="num">Quantity #</th>
</tr>
</thead>
<tbody>
<?php foreach ($dbh->query($query) as $row) {?>
<tr>
<td class="ui-widget-content"><input type="checkbox" class="check" name="check" id="checkid-<?php echo intval ($row['ID'])?>"></td>
<td class="loc ui-widget-content" data-loc="<?php echo $row['Loc'] ?>"><input type="hidden"><?php echo $row['Loc'];?></td>
<td class="rp-code ui-widget-content" align="center" data-rp-code="<?php echo $row['Rp-Code'] ?>" id="rp-code-<?php echo intval ($row['Rp-Code'])?>"><?php echo $row['Rp-Code'];?></td>
<td class="sku ui-widget-content" data-sku="<?php echo $row['SKU'] ?>" id="sku-<?php echo intval ($row['SKU'])?>"><?php echo $row['SKU'];?></td>
<td class="special-id ui-widget-content" data-special-id="<?php echo $row['Special-ID'] ?>" align="center" id="special-id-<?php echo intval ($row['Special-ID'])?>"><?php echo $row['Special-ID'];?></td>
<td class="description ui-widget-content" data-description="<?php echo htmlspecialchars($row['Description']) ?>" id="description-<?php echo intval ($row['Description'])?>"><?php echo $row['Description'];?></td>
<td class="quantity ui-widget-content" data-quantity="<?php echo $row['Quantity'] ?>" align="center" id="quantity-<?php echo intval ($row['Quantity'])?>"><?php echo $row['Quantity'];?></td>
<td class="unit ui-widget-content" data-unit="<?php echo $row['Unit'] ?>" id="unit-<?php echo intval ($row['Unit'])?>"><?php echo $row['Unit'];?></td>
<td style="display: none;" class="quantity_num ui-widget-content"><input type="textbox" style="width: 100px;" class="spinner" id="spin-<?php echo intval ($row['ID'])?>"></td>
</tr>
<?php } ?>
</tbody>
</table>
JavaScript for keeping checked checkboxes, checked, throughout the session:
$(function(){
$(':checkbox').each(function() {
var $el = $(this);
$el.prop('checked', sessionStorage[$el.prop('id')] === 'true');
});
$('input:checkbox').on('change', function() {
var $el = $(this);
sessionStorage[$el.prop('id')] = $el.is(':checked');
});
});
JavaScript that brings in data from table to email:
function sendMail() {
var link = "mailto:me#example.com"
+ "?subject=" + encodeURIComponent("Order")
+ "&body=";
var body = '';
$('table tr input[name="check"]:checked').each(function(){
var current_tr = $(this).parent().parent();
var data = current_tr.find('.loc').data('loc');
body += encodeURIComponent(data) + '\xa0\xa0';
var data =current_tr.find('.rp-code').data('rp-code');
body += encodeURIComponent(data) + '\xa0\xa0';
var data =current_tr.find('.sku').data('sku');
body += encodeURIComponent(data) + '\xa0\xa0';
var data =current_tr.find('.special-id').data('special-id');
body += encodeURIComponent(data) + '\xa0\xa0';
var data =current_tr.find('.description').data('description');
body += encodeURIComponent(data) + '\xa0\xa0';
var data =current_tr.find('.quantity').data('quantity');
body += encodeURIComponent(data) + '\xa0\xa0';
var data =current_tr.find('.unit').data('unit');
body += encodeURIComponent(data) + '\xa0\xa0';
var data =current_tr.find('.spinner').data('spinner');
body += encodeURIComponent(data) + '\xa0\xa0';
body += '%0D%0A';
});
body += '';
link += body;
console.log(link);
window.location.href = link;
}
Revised based your comments/new code:
Even with your new pasted code, the issue still remains that you can only output whats currently available on screen due looping over the table rows. Instead you need to take it a step further and build objects to house the information you need for building your email, then place those objects in storage for later retrieval.
Again looking at your code your checkboxes have a prefix of "check-id".
$('input:checkbox').on('change', function() {
var $el = $(this);
var key = $el.prop('id');
var rowObject = {};
//check if already in storage
if(sessionStorage.getItem(key) !== null){
rowObject = JSON.parse(sessionStorage.getItem(key));
rowObject.checkedVal = $el.is(':checked'); //update it's check value
}else{
//build entire row object
var current_tr = $(this).parent().parent();
rowObject.loc = current_tr.find('.loc').data('loc');
rowObject.rpCode = current_tr.find('.loc').data('rp-code');
rowObject.sku = current_tr.find('.loc').data('sku');
//etc. as many pieces as you need
}
//set to session
sessionStorage.setItem(key, JSON.stringify(rowObject));
});
//then later for your send email method
function sendEmail(){
var link = "mailto:me#example.com"
+ "?subject=" + encodeURIComponent("Order")
+ "&body=";
var body = '';
//loop over the row objects instead
$.each(sessionStorage, function(key, value){
//sort out the ones we want
if(key.indexOf("checkid-") > -1){
var rowObject = JSON.parse(sessionStorage.getItem(key));
body += encodeURIComponent(rowObject.loc + '\xa0\xa0');
body += encodeURIComponent(rowObject.rpCode + '\xa0\xa0');
body += encodeURIComponent(rowObject.sku + '\xa0\xa0');
//etc. as many pieces as you need
body += '%0D%0A';
}
});
//whatever other logic you have
}
I haven't fully tested this code for your purposes but you get the idea, build your objects then use those during your iteration.

Categories