I know this question gets asked alot but i have tried all of the clickevents for but cant seem to get this to work i am trying to get a value or string from a td here is the table i build
<table id="tblMain">
<thead>
<tr>
<th>Parcel ID</th>
<th>Quick Ref ID</th>
<th>Address</th>
<th>Tax Unit</th>
<th>Style</th>
<th>Arch Style</th>
<th>Validity Code</th>
<th>Sale Price</th>
<th>Sale Date</th>
<th>Year Built</th>
<th>Total Living Area</th>
<th>Lot Area</th>
<th>Bedrooms</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr class="side-link">
<td class="parcelIDCell"><a id="Parcelid" /> #item.ParcelId </td>
<td>#item.QuickRefId</td>
<td>#item.Address</td>
<td>#item.TaxunitA</td>
<td>#item.StyleA</td>
<td>#item.ArchStyleA</td>
<td>#item.ValCode</td>
<td>#item.SalePriceA</td>
<td>#item.SaleDateA</td>
<td>#item.YearBuilt</td>
<td>#item.LivingArea</td>
<td>#item.LotArea</td>
<td>#item.BedroomA</td>
#*<td>#item.ParcelID</td>
<td>#item.PropertyID</td>*#
</tr>
}
</tbody>
i just want to retrieve the parcel Id from the first row depending on which one i click on
some java script i have tried
<script>
var tbl = document.getElementById("tblMain");
if (tbl != null) {
for (var i = 0; i < tbl.rows.length; i++) {
for (var j = 0; j < tbl.rows[i].cells.length; j++)
tbl.rows[i].cells[j].onclick = function () { getval(this); };
}
}
function getval(cel) {
alert(cel.innerHTML);
}
there is more but i deleted them
Any advice would be greatly appreciated
you want either an id or the string? You can do this:
$("td").click(function() {
if($(this).hasClass("parcelIDCell")){
var ID = $(this).find("a").attr("id");
alert("Id is: " + ID);
}else{
var String = $(this).text();
alert("Text is: " + String);
}
});
It checks to see if the td being clicked has the class parcelIDCell, if it does it will find the a tag inside it and pull the id. If the class does not exist, it will just grab the text instead. Fiddle below:
FIDDLE
With jQuery:
$("#tblMain td").click(function() {
if ($(this).hasClass('parcelIDCell') {
alert($(this).find('a').attr('id));
} else {
alert($(this).text());
}
});
Update: getting the parcel id or the text, depending on the class of the td.
Related
I'm making a web-based POS. I have two table, one is for displaying the search products using jquery and when I clicked the product it will transfer to the second table. So my second table is dynamically dependent of what the user clicked. This is my table look like with css.
I want to get the total price of Sub.Total column automatically and display to the bottom specially in the Total p tag.
This is my html table code.
<table id="table2">
<thead>
<tr>
<th>Barcode</th>
<th>Description</th>
<th>Price</th>
<th>Unit</th>
<th>Qty</th>
<th>Sub.Total</th>
<th>Action</th>
</tr>
</thead>
<tbody id="tableData">
</tbody>
</table>
<table id="table1">
<thead>
<tr>
<td>Barcode</td>
<td>Product Name</td>
<td>Price</td>
<td>Unit</td>
<td>Stocks</td>
</tr>
</thead>
<tbody id="products">
</tbody>
</table>
This is my query from search box.
$show = "SELECT * FROM products WHERE product_name LIKE '$name%' ";
$query = mysqli_query($db,$show);
if(mysqli_num_rows($query)>0){
while($row = mysqli_fetch_array($query)){
echo "<tr class='js-add' data-barcode=".$row['id']." data-product=".$row['product_name']." data-price=".$row['sell_price']." data-unt=".$row['unit']."><td>".$row['id']."</td><td>".$row['product_name']."</td>";
echo "<td>₱".$row['sell_price']."</td>";
echo "<td>".$row['unit']."</td>";
echo "<td>".$row['quantity']."</td>";
}
}
This is for displaying the cliked rows from searched products.
$('body').on('click','.js-add',function(){
var target = $(this);
var product = target.attr('data-product');
var price = target.attr('data-price');
var barcode = target.attr('data-barcode');
var unit = target.attr('data-unt');
swal("Enter number of item to buy:", {
content: "input",
})
.then((value) => {
if (value == "") {
swal("Error","Entered none!","error");
}else{
var qtynum = parseInt(value);
if (isNaN(qtynum)){
swal("Error","Please input a valid number!","error");
}else{
var total = value * price;
$('#tableData').append("<tr><td>"+barcode+"</td
<td>"+product+"</td>
<td>"+accounting.formatMoney(price,{symbol:"₱",format: "%s %v"})+"</td><td>"+unit+"</td>
<td>"+value+"</td>
<td class='totalPrice'>"+accounting.formatMoney(total,{symbol:"₱",format: "%s %v"})+"</td>
<td><button class='btn btn-danger' type='button' id='delete-row'>×</button><tr>");
}
}
});
});
I'd tried this code but it return NaN.
$(document).ready(function(){
var TotalValue = 0;
$("#tableData tr").each(function(){
TotalValue += parseFloat($(this).find('.totalPrice').text().replace(/,/g, "₱"));
});
alert(TotalValue);
});
I'd tried modifying the code but I cant get the job done. Hope someone will help about this one. Thanks in advance.
Edit: Updated answer.
Based off what you tried here would be a working solution using your logic.
$(document).ready(function(){
var TotalValue = 0;
var TotalPriceArr = $('.totalPrice').get()
$(TotalPriceArr).each(function(){
TotalValue +=parseInt($(this).text().replace('₱', ''))
});
alert(TotalValue);
});
Active learner here, trying to figure out how to create a JSON object out of HTML table. I only want the value of one specific TD and want to give each value an incrementing number as a key. I'd like an output like below. My table has a TD for the city names, but it does not have one with a incrementing numerical value so I'd need to add that another way.
{
"mycities" : [
{
"Seattle" : "1",
"Chicago" : "2",
"New York" : "3"
"Pitt" : "4",
"LA" : "5",
"Fresno" : "6"
},
]
}
Here is what my table looks like:
<table>
<thead>
<tr>
<th>city name</th>
<th>other city info</th>
</tr>
</thead>
<tbody>
<tr>
<td>Seattle</td>
<td>Lots of rain</td>
</tr>
etc,etc,etc
</tbody>
</table>
I've tried using a replacer function but haven't got it figured out after much googling. Any help is appreciated!
$(document).ready(function(){
$("body").on("click",".submitButtonPri",function(){
count= 1;
function replacer(key, value) {
if (typeof value === 'string') {
return count;
}
return value;
}
var myRows = [];
var $headers = $(".rightDash > table thead th");
var $rows = $(".rightDash > table tbody tr").each(function(index) {
$cells = $(this).find("td.titlePri");
myRows[index] = {};
$cells.each(function(cellIndex) {
myRows[index][$($cells[cellIndex]).text()] = $(this).text();
});
count++;
});
var myObj = {};
myObj.myrows = myRows;
console.log(JSON.stringify(myObj,replacer));
});
});
Use reduce to iterate over the trs in the body, using the text content of the first td in the tr as the city name. The third argument to the function provided to reduce represents the iteration index:
const cityData = [...document.querySelectorAll('tbody > tr')]
.reduce((a, tr, i) => {
a[tr.children[0].textContent] = i + 1;
return a;
}, {});
console.log(
{ mycities: [
cityData
]}
);
<table>
<thead>
<tr>
<th>city name</th>
<th>other city info</th>
</tr>
</thead>
<tbody>
<tr>
<td>Seattle</td>
<td>Lots of rain</td>
</tr>
<tr>
<td>Chicago</td>
<td>Lots of rain</td>
</tr>
<tr>
<td>New York</td>
<td>Lots of rain</td>
</tr>
</tbody>
</table>
You can start with this simple script:
$('td').each(function(index, obj) {console.log(index, $(this).html())});
It returns all what you need and you just need assemble JSON by any way
I have a table that is being populated from database through an angularJS array.
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>Code</th>
<th>Description</th>
<th>Budget Amount</th>
<th>Actual Amount</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="lineItem in vm.budget.budgetLines">
<td>
{{lineItem.code}}
</td>
<td>#{{lineItem.description}}</td>
<td>{{lineItem.budgetAmount | currency}}</td>
<td><input type="number" class="form-control" ng-model="lineItem.actualAmount" required /></td>
</tr>
</tbody>
</table>
The data population works fine. But if you look at the table, you would notice an input field in the last column. I need to be able to perform an update with changes made to the input for which I need just the 1st and last column for the operation. I used the following approach but it didn't work because it just used the original values with which the table was first populated.
$scope.lineItems = [];
for (var i = 0; i < vm.budget.budgetLines.length; i++) {
var lineItem = vm.budget.budgetLines[i];
$scope.lineItems.push({
'code': lineItem.code,
'actualAmount': lineItem.actualAmount
});
}
So I thought of using pure javascript inside my angular controller to loop through the table rows and push the columns I need in the array like so;
var myTable = document.getElementById("tblValues");
var current, cell;
for (var i = 0; i < myTable.rows.length ; i++) {
var rowItem = myTable.rows[i];
$scope.lineItems.push({
'code': rowItem.cells[1],
'actualAmount': rowItem.cells[4].children[0].value
});
}
But an error is thrown in the console: rowItem.cells[4].children[0] is undefined
Please how can I get this to work just the way I want it?
I got it to work just the way I desired it to.
var myTable = document.getElementById("tblValues");
var current, cell;
$scope.lineItems.length = 0;
for (var i = 0; i < myTable.rows.length ; i++) {
var rowItem = myTable.rows[i + 1];
$scope.lineItems.push({
'code': rowItem.cells[1].innerText,
'actualAmount': rowItem.cells[4].firstChild.value
});
}
I've a bit of experience coding in php but am fairly new to js. What I'm trying to do in js is create a simple order form, each line is to have a text box indicating the quantity to be ordered, product name and product price, with the latter to be populated from product array prod. My fairly rudimentary first attempt appears below, which needless to say doesn't work.
<body onload="populate()">
<table id="demo">
<thead>
<tr>
<th>Quantity</th>
<th>Product</th>
<th>Price</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script>
function populate(){
var prod; //array of objects with name and price attributes
var table = document.getElementById("theTable");
for (var i=0; i<prod.length; i++)
{
var newTr = table.insertRow(-1);
var numOrdered=document.createElement('input');
numOrdered.type='text';
numOrdered.id= "product "+i; //assigning id of "product i" to each product i
newTr.insertCell(0).appendChild(num);
newTr.insertCell(-1).appendChild(document.createTextNode(prod["name"]));
newTr.insertCell(-1).appendChild(document.createTextNode(prod["price"]));
}
}
</script>
</body>
Any and all help appreciated.
have a look at the snippet at the bottom.
what's changed is:
in this line you targeted the wrong id, should have been 'demo'
var table = document.getElementById("theTable");
you also needed to reference the correct value in your array inside the loop:
document.createTextNode(prod["name"]);
to:
document.createTextNode(prod[i]["name"]);
and lastly this line:
newTr.insertCell(0).appendChild(num);
to:
newTr.insertCell(0).appendChild(numOrdered);
hope this helps.
function populate() {
var prod = [{
name: 'box',
price: 20
}, {
name: 'plane',
price: 40
}]; //array of objects with name and price attributes
var table = document.getElementById("theTable");
for (var i = 0; i < prod.length; i++) {
var newTr = table.insertRow(-1);
var numOrdered = document.createElement('input');
numOrdered.type = 'text';
numOrdered.id = "product " + i; //assigning id of "product i" to each product i
newTr.insertCell(0).appendChild(numOrdered);
newTr.insertCell(-1).appendChild(document.createTextNode(prod[i]["name"]));
newTr.insertCell(-1).appendChild(document.createTextNode(prod[i]["price"]));
}
}
populate();
<table id="theTable">
<thead>
<tr>
<th>Quantity</th>
<th>Product</th>
<th>Price</th>
</tr>
</thead>
<tbody></tbody>
</table>
Try This code:
I am using jQuery, to create, append and iterating the array(each Loop).It is a better and effective way. Please use jQuery for DOM manipulation.
HTML:
<table id="demo">
<thead>
<tr>
<th>Quantity</th>
<th>Product</th>
<th>Price</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
CSS:
table,td{display:block}
th{width:100px}
td{margin:10px}
JS:
var prod=[{product:'samsung',price:100},{product:'apple',price:200},{product:'micromax',price:300}];
(function($){
$.each(prod,function(index,value){
$('#demo th:eq(0)').append("<td><input type='text'></td>");
$('#demo th:eq(1)').append("<td>"+value.product.toUpperCase()+"</td>");
$('#demo th:eq(2)').append("<td>"+value.price+"</td>")
});
})(jQuery);
Here is the JSFiddle Link:
https://jsfiddle.net/Dee0565/8vww1pwf/
i want to apply style to even/odd rows of a table, i know its super easy with css and jquery. but i am trying to put that table in windows gadget and this below code only works in browser not in that gadget.
table.data-Tables tbody tr:nth-child(even){
background-image: none;
background:#ECF0F1;
}
The Above Code i have tried with CSS do not work, css do works but some codes of css do not work on gadget, may be new css is not acceptable by gadgets..
But anyhow if CSS do not works then i want to try javascript.
Can anyone make it possible in java script to add some styles to even row.
Table:
<table class="data-Tables" cellpadding=0 cellspacing=0 border=0>
<thead>
<tr>
<th>Room</th>
</tr>
</thead>
<tbody>
<tr>
<td>Admin Room No: 36</td>
</tr>
<tr>
<td>Director Room No: 36</td>
</tr>
</tbody>
</table>
You can iterate over the rows and add a class to just the even ones. If they don't have any other class value, then:
function addClassToEvenRows(table) {
var rows = table.rows;
for (var i=0, iLen=rows.length; i<iLen; i++) {
rows[i].className = i%2? '' : 'even';
}
}
will do the trick. If there might be other class values, then:
function addClassToEvenRows(table) {
var rows = table.rows;
var className;
for (var i=0, iLen=rows.length; i<iLen; i++) {
if ((i + 1)%2) {
rows[i].className += (rows[i].className.length? ' ' : '') + even;
}
}
}