Sending selective data from dynamic table - javascript

I have a dynamic table with some data and total counting with JS, when checkbox is ticked row is removed from count.
I need a way to send first ID field and total price to another php page for rows where checkbox is ticked.
As seen on picture below I need to send vales 8, 10 and 15 with total 1500.
I have given every checkbox an unique id and value of same id.
<table id="price-list">
<tr>
<td>Some data</td>
<td>
<input class="w3-check" type="checkbox" checked="" value="<?php echo $row['rad_id']?>" id="<?php echo $row['rad_id']?>">
</td>
</tr>
<tfoot>
<tr class="totalColumn">
<td><span> Ukupno:</span></td>
<td class="total price">0.00 kn</td>
</tr>
</tfoot>
</table>
Closest that I got is reading whole table with JS, with another script putting it into submit value and passing it into another PHP page.
<form action="spec-provjera.php" method="POST">
<input type="button" id="bt" value="Show Table Data" onclick="showTableData()" />
<!-- <input type="submit" name="submit" value="info" id="info" onclick="myFunction()"/> -->
<script>
function showTableData() {
document.getElementById('info').innerHTML = "";
var myTab = document.getElementById('price-list');
// LOOP THROUGH EACH ROW OF THE TABLE AFTER HEADER.
for (i = 1; i < myTab.rows.length; i++) {
// GET THE CELLS COLLECTION OF THE CURRENT ROW.
var objCells = myTab.rows.item(i).cells;
// LOOP THROUGH EACH CELL OF THE CURENT ROW TO READ CELL VALUES.
for (var j = 0; j < objCells.length; j++) {
info.innerHTML = info.innerHTML + ' ' + objCells.item(j).innerHTML;
}
info.value = info.innerHTML + '<br />'; // ADD A BREAK (TAGG)
}
}
</script>
<script>
function myFunction() {
var info = document.getElementById("info").value;
$.ajax({
type : "POST", //type of method
url : "spec-provjera.php", //your page
data : { info : value.info},// passing the values
success: function(res){
//do what you want here...
}
});
}
</script>
<button class="w3-btn w3-right w3-deep-orange" type="submit" name="izrada" id="info" onclick="myFunction()"/>KREIRAJ test</button>
</form>
This passes all table contains into spec-provjera.php with AJAX but this way is totally messy and posts all rows with check-boxes all set too checked.
Id be happy if I could just filter out cheeked row's.
Can someone suggest a way to do this, keep in mind I'm not very good with JS.

Found a solution:
I wrapped whole table as form then made dynamic checkbox unique field and same value "da" like this:
<input class="w3-check" type="checkbox" checked="" name="<?php echo $row['rad_id']?>" value="da">
Also made an total price field an input with read only like this:
$("tfoot .total.price",tbl).html( '<input type="post" id="total" readonly size="5" value="' + t.toFixed(2) + '" name="total"> kn');
Then I'm doing on other PHP page this:
foreach($_POST as $key => $value) {
echo "POST parameter '$key' has '$value'</br> " ;
}
Witch if i uncheck id 14 as seen on first picture gives me:
POST parameter '8' has 'da'
POST parameter '10' has 'da'
POST parameter '15' has 'da'
POST parameter 'total' has '1500.00'
As seen i have only checked items with total price. Now i can manipulate this as needed in PHP.

Related

send one or zero with checkbox click in JS

I currently have a form with a loop that builds multiple checkboxes where I can successfully trigger an event.
I have my code set so that if the value from the database for the row is 1 then pre-check the box, which works.
I'm trying to make it so that when the box is checked, Javascript sends a '1' but if it's unchecked then it sends a '0'.
If the page loads with the database value of 1, and the box is checked, then when the user unchecks it I want it to send '0' to the console log and vice versa
<form id="saveLineup">
#foreach($list as $lists)
<tr style="text-align:center;">
<td><input class="addToLineup" type="checkbox" <?php if ($lists['LINE_UP'] == 1) echo "checked='checked'"; ?></td>
</tr>
#endforeach
</form>
currently, no matter what, the checkbox triggers the value 'on' to show on console.log, whether I check or uncheck it.
What am I doing wrong?
$(".addToLineup").click(function (e) {
updatedata.lineup = $(".addToLineup").val();
console.log(updatedata);
});
<form id="saveLineup">
#foreach($list as $lists)
<tr style="text-align:center;">
<td>
<input class="addToLineup" type="checkbox"/>
</td>
</tr>
#endforeach
</form>
Edit: After clarification, you simply need a check for status of the checkbox when it's clicked, then send 1 or 0 based on that:
$(".addToLineup").click(function(e) {
if ($(this).is(":checked")) {
updatedata.lineup = 1;
} else {
updatedata.lineup = 0;
}
console.log(updatedata);
});
JSFiddle for reference: https://jsfiddle.net/1agLdu5e/1
You should set the values of the checkboxes to something that identifies the particular lineup. Then use an array-style name for the input. The result will be that $_POST['addToLineup'] will be an array of all the identifiers.
<form id="saveLineup">
#foreach($list as $lists)
<tr style="text-align:center;">
<td><input class="addToLineup" name="addToLineup[]" type="checkbox" value="<?php echo $lists['ID']; ?>" <?php if ($lists['LINE_UP'] == 1) echo "checked='checked'"; ?></td>
</tr>
#endforeach
</form>
Replace 'ID' with the actual name of the table column containing the lineup ID.

Find the sum of a column in html table using Jquery or JS

I have a html table created using jQuery:
success: function(data, textStatus, errorThrown) {
var rows ="";
function formatItem(data) {
return '<td>'+data.name + '</td> <td> ' + data.price + ' </td><td>' + "<input></input>" +'</td>';
}
$.each(data, function (key, item) {
$('<tr>', { html: formatItem(item) }).appendTo($("#foodnames"));
});
}
This is what the interface looks like:
The table is working fine with all the data showing.
The problem is finding the sum of the third column. Where I can enter a number and display it using an id.
Is there anyway to do it?
What you want to do is to use jQuery to select the table, and all of the third td's for each row, then sum it. The basic pseudocode is:
Clear the output box.
ForEach TR
Select the third TD
Add that value to the output box.
End ForEach
To do that in jQuery, you just need to know how to select the right values. Assigning relevant class/id names is helpful.
I put together a basic example that you can run. It will tabulate the total of the third column dynamically, as you change the value. I hard coded the price column, but you could easily put some other values or input there.
I put it in an onChange event handler, but if you are loading the data from a server or something, you could do document onLoad or whenever your ajax is complete.
//trigger an event when the input receives a change
$("#exampleTableContainer table td input").off("change").on("change", function(ele) {
//clear the out put box
$("#totalOut").val("0");
//for the table container, select all tr's within the table's tbody.
//Excluding tbody will also select the thead.
$("#exampleTableContainer table tbody tr").each(function(index, rowElement) {
//tablulate the cost of the current row
var rowCost = parseInt($(rowElement).find(".cost").text()) * parseInt($(rowElement).find(".amount input").val());
//if the rowCost is a valid number, add it to whatever is in the output box
if (rowCost) $("#totalOut").val(parseInt($("#totalOut").val()) + rowCost)
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="exampleTableContainer">
<table>
<thead>
<tr>
<th class="item">Item</th>
<th class="cost">Cost</th>
<th class="amount">Amount</th>
</tr>
</thead>
<tbody>
<tr>
<td class="item">Item 1</td>
<td class="cost">123</td>
<td class="amount">
<input type="number">
</td>
</tr>
<tr>
<td class="item">Item 2</td>
<td class="cost">1</td>
<td class="amount">
<input type="number">
</td>
</tr>
<tr>
<td class="item">Item 3</td>
<td class="cost">2</td>
<td class="amount">
<input type="number">
</td>
</tr>
<tr>
<td class="item">Item 4</td>
<td class="cost">4</td>
<td class="amount">
<input type="number">
</td>
</tr>
</tbody>
</table>
<br>
<div>
Total:
<input id="totalOut" readonly value="0">
</div>
</div>
I'm not sure if you plan to use this in a production environment or not, so maybe this is overkill for what you're trying to accomplish, but I would recommend using an underlying data model bound to the table. Then you can get your sum from your data:
const data = [
{food: "Veggie burger", price: 200, qty:1},
// ...Add as many food items as you like
]
You would be able to use the data to build your table:
// Get a reference to the table and create a document fragment
const table = document.getElementById("table-body");
const body = document.createDocumentFragment();
// Fill the fragment with your data:
data.map((value, key) => {
// Row-building logic goes here
// this probably isn't what you actually do here:
const row = document.createElement("tr");
row.className = key;
for (let x in value) {
const dataCell = document.createElement("td");
dataCell.className = x;
dataCell.innerHTML = value[x];
row.appendChild(dataCell);
}
body.appendChild(row);
});
table.innerHTML = "";
table.appendChild(body);
Then you can calculate your sum based on the data, not the UI:
const subTotal = data
.map((value) => value.price * value.qty)
.reduce((a, b) => a + b);
document.getElementById("total").textContent = subTotal;
You would set an event listener on the table(parent node) and use event.target to find the row and column (.qty in this case) and update the corresponding field (qty) in the data object when the input is changed.
$("#my-table").on("input", (e) => {
// You would probably be better off using a custom attribute than a class since there can be multiple classes, but we'll use class to keep it simple:
const column = $(e.target).parent("td").attr("class");
const row = $(e.target).parent("td").parent('tr').attr("class");
data[row][column] = e.target.value;
console.log(data);
});
This pattern also makes it easy to send the updated data back to the REST API to update your database later.
https://jsfiddle.net/79et1gkc/
I know you said you're using jQuery, but ES6 is much nicer in my opinion.
Try this:
$(document).ready(function(){
var total = 0;
$("#submit").click(function(){
$(".user_input").each(function(){
var value = parseInt($(this).val());
total += value;
});
$("#output").text(total);
});
});
HTML
<input type="text" name="value1" class="user_input"/>
<input type="text" name="value2" class="user_input"/>
<input type="text" name="value3" class="user_input"/>
<button name="submit" id="submit" value="calculate">
Calculate
</button>
<div>
<span>Total:</span><div id="output">
</div>

How to set index variables in filters and selectors jquery

I have the following row structure that serves as a template to clone it and add it to a table each time a user presses an "Add" button, This template is hidden:
<tr class="plantilla">
<td>
<select class="cmb_arboles" id="cmb_arboles" name="arboles[]">
</select>
</td>
<td>
<input type="text" id="txttoneladas" name="txttoneladas[]"/>
</td>
<td>
<input type="text" id="txtprecio" name="txtprecio[]"/>
</td>
<td>
<select id="cmb_destino" name="destino[]">
</select>
</td>
<td class="eliminar_fila">
Eliminar
</td>
</tr>
When the "add" button is pressed, invokes:
$("#agregar").click(function()
{
nid++;
$("#plantilla tbody tr:eq(0)").clone().attr("id",nid).appendTo("#plantilla tbody");
$("#plantilla tbody tr:eq(nid)").find("td:eq(0)").find("select").attr("id","cmb_arboles_"+nid);
});
The first line, generates the sequence of the row number. The second line clones the entire template as a new row in the table and adds an id = nid to the .
The third line, accesses the row and looks for the select to add the nid sequential to the select id, but this does not work. When doing several tests, I conclude that the problem is that "tr: eq (nid)" does not accept the nid as variable, because when changing the nid by a specific integer, for example 1, it works, adding id to select. The question here is how to put the nid as a parameter in the: eq () so that it works correctly and do what I have explained ????
The same situation happens in the following line of code:
$(document).on('change', '.cmb_arboles', function () {
var $select = $(this);
var $row = $select.closest('tr');
var idd = $row.attr('id');
var valor=$("#tabla tbody tr[id=idd]").find("td:eq(0)").find("select").val();
});
Of lines 1 to 3, you get the number of the row in which you have selected in the select component.
The last line gets the value of the select that was selected, with the information of the row number where the selection was made, but this does not work. When doing several tests, I conclude that the problem is in "tr [id = idd]", which does not correctly process the variable "idd". I made the test of changing the idd by a specific integer, for example 1 and then I generate a new line in the table with id = 1 and the line of code works correctly, returning the option that was selected in the select element.
With these two examples, I want to check if someone can tell me how to place the parameters I mentioned in the two cases, so that the functionality is executed correctly and does what is expected.
I will be enormously grateful.
the issue is you have to give
("#plantilla tbody tr:eq(nid)" as (("#plantilla tbody tr:eq('"+nid+"')"
I have created a fiddle. check it out. I didn't use jquery for the same.
<style>
#template {
display: none;
}
</style>
<table><tbody id="template">
<tr class="plantilla">
<td>
<select class="cmb_arboles" id="cmb_arboles" name="arboles[]">
</select>
</td>
<td>
<input type="text" id="txttoneladas" name="txttoneladas[]" />
</td>
<td>
<input type="text" id="txtprecio" name="txtprecio[]" />
</td>
<td>
<select id="cmb_destino" name="destino[]">
</select>
</td>
<td class="eliminar_fila">Eliminar</td>
</tr></tbody>
</table>
<input type="button" id="agregar" value="Add">
<table>
<tbody id="plantilla"></tbody>
</table>
<script>
var nid = -1;
document.getElementById('agregar').onclick = function(){
var table = document.getElementById('plantilla');
var newRow = document.getElementById('template').innerHTML;
nid++;
newRow = newRow.replace('id="cmb_arboles"', 'id="cmb_arboles_'+nid+'"');
newRow.replace('id="cmb_arboles"', 'id="cmb_arboles_'+nid+'"');
table.innerHTML += newRow;
}
</script>
https://jsfiddle.net/nugee3s6/
You are hard coding the id value in $("#tabla tbody tr[id=idd]") not using the variable above it
If you wanted to use the variable it would be:
$("#tabla tbody tr[id=" +idd +"]")
But it makes no sense to use the ID to search again for the same row since you already have that row element as $row
So change to:
$(document).on('change', '.cmb_arboles', function () {
var $select = $(this);
var $row = $select.closest('tr');
var valor=$row.find("td:eq(0) select").val();
});
Then don't worry about using ID's, you don't need them

escape parameters on onclick event doesnt work

I'm atm working on getting a dynamic table into an html page with a button on every table row's first column to display a description of an item(it's an itemlist).
however when setting the innerhtml with an onclick event i am not able to fire an alert .When i want to call another JS function to call the alert and trying to pass an argument in my onclick function it wont do nothing, when trying to escape the quotes nothing works.
Javascript
function showAuctionList(auctionList){
var table = document.getElementById("myTableData");
for(var i = 0 ; i< auctionList.length ; i++){
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var description = auctionList[i].itemDesc;
row.insertCell(0).innerHTML= '<input type="button" value = "Show Description" onclick="showDescription( description)">';
row.insertCell(1).innerHTML= auctionList[i].auctionId;
row.insertCell(2).innerHTML= auctionList[i].sellId;
row.insertCell(3).innerHTML= auctionList[i].startDate;
row.insertCell(4).innerHTML= auctionList[i].endDate;
row.insertCell(5).innerHTML= auctionList[i].buyNow;
row.insertCell(6).innerHTML= auctionList[i].minBid;
row.insertCell(7).innerHTML= auctionList[i].actualBid;
row.insertCell(8).innerHTML= auctionList[i].itemCat;
row.insertCell(9).innerHTML= auctionList[i].itemName;
row.insertCell(10).innerHTML= auctionList[i].itemDesc;
}
}
function showDescription(desc){
alert(desc);
}
HTML
<div id="search" style="display:none">
<button id="searchButton" onclick="
google.script.run.withSuccessHandler(showAuctionList).getAuctionList()"> Search </button> <br>
<div id="mydata">
<table id="myTableData" border="1" cellpadding="2">
<tr>
<td> </td>
<td><b>Auction ID</b></td>
<td><b>Seller ID</b></td>
<td><b>Start Date</b></td>
<td><b>End Date</b></td>
<td><b>Buy now option</b></td>
<td><b>Min Bid</b></td>
<td><b>Actual Bid</b></td>
<td><b>Category</b></td>
<td><b>Item Name</b></td>
<td><b>Description</b></td>
</tr>
</table>
<br/>
</div>
gs function call:
function doget(e){
...
return HtmlService.createTemplateFromFile('Main').evaluate().setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
can this be escaped that description works as an parameter or whats the workaround about the issue?The rest works perfectly fine though
Try this. As description seems to be a string value you need to surround it with qoutes.
row.insertCell(0).innerHTML = '<input type="button" value = "ShowDescription" onclick="showDescription(\'' + description + '\');">';
You need not escape if use this code:
row.insertCell(0).innerHTML= '<input type="button" value = "Show
Description" onclick="showDescription(this.getAttribute(\'description\'))">';
row.cells[0].firstChild.setAttribute('description', description);

Total of a particular column from html table having multiple rows

My Java Script Code
<script>
$(function(){
$('#addRow').click(function(){
var html = $('#row_template').html();
$('#dataTable').append(html);
$(".tablerow").each(function(index) {
$(this).html(index + 1);
});
});
$('#deleteRow').click(function(){
$('#dataTable .mychkbox:checked').parents('tr').remove();
});
$('#dataTable').on('change','.select-desc',function(){
var cur_val = $(this).val();
$(this).parents('tr').find('input[name="rate[]"]').val(cur_val);
});
$('#dataTable').on('keyup','input[name="qty[]"]', function(){
var qty = +$(this).val();
var unit = +$(this).parents('tr').find('input[name="rate[]"]').val();
$(this).parents('tr').find('input[name="amt[]"]').val(qty*unit);
var totamt = 0 ;
var theTbl = document.getElementById('dataTable');
for(var i=0;i<theTbl.length;i++)
{
for(var j=0;j<theTbl.rows[i].cells.length;j++)
{
totamt = totamt + theTbl.rows[i].cells[4].InnerHTML;
}
}
});
});
</script>
My HTML Code is
<!DOCTYPE html>
<html>
<div class="left">
<h2><span class="orange">Work Order Items</span></h2>
<table>
<tr>
<td><input type="button" value="Add Row" id="addRow" /></td>
<td><input type="button" value="Remove Row" id="deleteRow" /></td>
</tr>
</table>
</div>
<table id="dataTable" class="form" border="0" width='100%'>
<tr>
<td></td>
<td>No</td>
<td>Item Description</label></td>
<td>Qty</td>
<td>Rate</td>
<td>Amount</td>
<td>Cert No</td>
<td>C Date</td>
</tr>
</table>
<table id="row_template" style="display:none">
<tr>
<td><input type="checkbox" name="chk[]" class="mychkbox" /></td>
<td class="tablerow"></td>
<td>
<?php
$sql = "SELECT itrate,CONCAT(itname,'|',itcode) as mname FROM ITMAST ";
$result = mysql_query($sql) or die(mysql_error());
echo "<select name='itname[]' id='itname' class='select-desc' >";
echo "<option value=''>-- Select Item --</option>";
while ($row = mysql_fetch_array($result))
{
echo "<option value = '{$row['itrate']}'";
if ($pitcode == $row['itrate'])
echo "selected = 'selected'";
echo ">{$row['mname']}</option>";
}
echo "</select>";
?>
</td>
<td><input type="text" name="qty[]" id="qty" size="6" class='rightJustified'></td>
<td><input type="text" name="rate[]" id="rate" size="8" class='rightJustified' readonly></td>
<td><input type="text" name="amt[]" id="amt" size="9" class='rightJustified' readonly></td>
<td><input type="text" maxlength="10" size="8" name="txtcertno[]"></td>
<td><input type="date" maxlength="10" size="10" name="txtcdate[]"></td>
</tr>
</table>
</html>
I am trying to take total of amount column i.e. amt[] after each entry of a row, but I am not getting it properly, I have written Javascript function for the same but some thing may be wrong in it
I did not correct all of your mistakes,
You should check #Samurai answer for more details (such as use of the 'id' and other things)
Main problem was, as I said in comment, use of innerHTML which returned "
another thing, your theTbl var was not good, you could never call .length on it. To solve that, you had to handle it this way :
var totamt = 0 ;
var theTbl = $('#dataTable');
//You are using jquery, so use jquery selectors...
var trs = theTbl.find("input[name='amt[]']");
//find there the AMT[] INPUTS, not the rows...
console.log("how many amt inputs? : "+trs.length);
for(var i=0;i<trs.length;i++)
{
//fetch the inputs, and make your calculations here
console.log("amount from row "+i+" = "+trs[i].value);
//do not forget, as Samurai said, to convert html to numeric...
$("#total").html(totamt+=parseFloat(trs[i].value));
}
Here is a working solution :
http://jsfiddle.net/nxm0ye54/20/
First to point out a few mistakes:
$('#row_template').html(): browsers automatically add tbody to the table, so you end up having multiple tbody in your main table which of course won't cause any problem on its own, if that's the desired output.
You're misusing ID. Each tr has multiple td with inputs that share the same ID. Instead you should use class.
To calculate the total amount you're getting the innerHTML of the cells which don't hold a number, but an input element. Instead you want the value these input elements are holding.
You need to convert the values to numbers before doing math on them, otherwise it will assume they're string and just put them beside each other. (e.g. 0+1+2 = 012 and not 3). You should use parseInt or parseFlout which the latter suits this case better.
A few modifications to your code:
$('#addRow').click(function () {
var html = $('#row_template tbody').html();
$('#dataTable tbody').append(html);
And - since you're using jQuery - I completely changed the calculation to a jQuery version:
//gt(0) cause the first row contains headers
//eq(5) cause we want the 6th cell (Amount)
var totamt = 0;
$('#dataTable tr:gt(0)').each(function() {
var newAmt = $(this).find('td:eq(5) input[type=text]').val();
totamt += parseFloat(newAmt);
});

Categories

Resources