Getting the table row values with jQuery - javascript

I am trying to get the values from an HTML table row. When I click on the table row delete button, I want to put those values on variables to send to the server. I have found something from here that looks like what I need, but when I put it together for my scenario, it does not work.
Here is the table HTML:
<table id='thisTable' class='disptable' style='margin-left:auto;margin-right:auto;' >
<tr>
<th>Fund</th>
<th>Organization</th>
<th>Access</th>
<th>Delete</th>
</tr>
<tr>
<td class='fund'>100000</td><td class='org'>10110</td><td>OWNED</td><td><a class='delbtn'ref='#'>X</a></td></tr>
<tr><td class='fund'>100000</td><td class='org'>67130</td><td>OWNED</td><td><a class='delbtn' href='#'>X</a></td></tr>
<tr><td class='fund'>170252</td><td class='org'>67130</td><td>OWNED</td><td><a class='delbtn' href='#'>X</a></td></tr>
<tr><td class='fund'>100000</td><td class='org'>67150</td><td>PENDING ACCESS</td><td><a class='delbtn' href='#'>X</a></td></tr>
<tr><td class='fund'>100000</td><td class='org'>67120</td><td>PENDING ACCESS</td><td><a class='delbtn' href='#'>X</a>
</td>
</tr>
and here is the jQuery:
var tr = $('#thisTable').find('tr');
tr.bind('click', function(event) {
//var values = '';
// tr.removeClass('row-highlight');
var tds = $(this).addClass('row-highlight').find('td');
$.each(tds, function(index, item) {
values = values + 'td' + (index + 1) + ':' + item.innerHTML + '<br/>';
alert(values);
});
alert(values);
});
What am I doing wrong? I keep looking at examples but I cant seem to make this work.

Try this:
jQuery('.delbtn').on('click', function() {
var $row = jQuery(this).closest('tr');
var $columns = $row.find('td');
$columns.addClass('row-highlight');
var values = "";
jQuery.each($columns, function(i, item) {
values = values + 'td' + (i + 1) + ':' + item.innerHTML + '<br/>';
alert(values);
});
console.log(values);
});
DEMO

Give something like this a try:
$(document).ready(function(){
$("#thisTable tr").click(function(){
$(this).find("td").each(function(){
alert($(this).html());
});
});
});​
Here is a fiddle of the code in action: https://jsfiddle.net/YhZsW/

All Elements
$('#tabla > tbody > tr').each(function() {
$(this).find("td:gt(0)").each(function(){
alert($(this).html());
});
});

Here is a working example. I changed the code to output to a div instead of an alert box. Your issue was item.innerHTML I believe. I use the jQuery html function instead and that seemed to resolve the issue.
<table id='thisTable' class='disptable' style='margin-left:auto;margin-right:auto;' >
<tr>
<th>Fund</th>
<th>Organization</th>
<th>Access</th>
<th>Delete</th>
</tr>
<tr>
<td class='fund'>100000</td><td class='org'>10110</td><td>OWNED</td><td><a class='delbtn'ref='#'>X</a></td></tr>
<tr><td class='fund'>100000</td><td class='org'>67130</td><td>OWNED</td><td><a class='delbtn' href='#'>X</a></td></tr>
<tr><td class='fund'>170252</td><td class='org'>67130</td><td>OWNED</td><td><a class='delbtn' href='#'>X</a></td></tr>
<tr><td class='fund'>100000</td><td class='org'>67150</td><td>PENDING ACCESS</td><td><a class='delbtn' href='#'>X</a></td></tr>
<tr><td class='fund'>100000</td><td class='org'>67120</td><td>PENDING ACCESS</td><td><a class='delbtn' href='#'>X</a>
</td>
</tr>
</table>
<div id="output"></div>​
the javascript:
$('#thisTable tr').on('click', function(event) {
var tds = $(this).addClass('row-highlight').find('td');
var values = '';
tds.each(function(index, item) {
values = values + 'td' + (index + 1) + ':' + $(item).html() + '<br/>';
});
$("#output").html(values);
});

$(document).ready(function () {
$("#tbl_Customer tbody tr .companyname").click(function () {
var comapnyname = $(this).closest(".trclass").find(".companyname").text();
var CompanyAddress = $(this).closest(".trclass").find(".CompanyAddress").text();
var CompanyEmail = $(this).closest(".trclass").find(".CompanyEmail").text();
var CompanyContactNumber = $(this).closest(".trclass").find(".CompanyContactNumber").text();
var CompanyContactPerson = $(this).closest(".trclass").find(".CompanyContactPerson").text();
// var clickedCell = $(this);
alert(comapnyname);
alert(CompanyAddress);
alert(CompanyEmail);
alert(CompanyContactNumber);
alert(CompanyContactPerson);
//alert(clickedCell.text());
});
});

Related

Disable and enable Select Value using Java Script

I am using below code.If i click Testing 1 or Testing 2 or selectAll,new rows will be created.I need to disable DatatType and Expected set value column if Execution Type is Get.If I select Set from Execution Type, DataType and Expected set value column should be enabled.How to implmente this? I am using this code in Html.erb file.How to create separate js method?
https://jsfiddle.net/bx5fa2vu/
$("#all").on("click", function() {
if ($(this).is(":checked")) {
let boxes = $("#paramTable input[type='checkbox']").not(this).not(":checked");
boxes.each(function() {
$(this).click();
});
} else {
let boxes = $("#paramTable input[type='checkbox']:checked").not(this);
boxes.each(function() {
$(this).click();
});
}
});
$("#paramTable input[type='checkbox']:not(#all)").on("click", function() {
if ($(this).is(":checked")) {
let name = $(this).parent("td").next("td").next("td").text().trim();
let newname = name.split('.').join('');
let newrow = $("<tr>");
let newcell = $("<td> ");
let newSel=$("<select class='ExeType' name='ExeTypeValue'><option value='getData'>Get</option><option value='SetData'>Set</option></select>")
newcell.append(newSel);
newrow.append(newSel);
let newcell1 = $("<td> ");
let newinput = $("<input type='text' class='parameterName' name='" + newname + "' id='" + newname + "' value='" + name + "'/>");
newcell1.append(newinput);
newrow.append(newcell1);
let newcells = $("<td><select class='parameterDscription' name='parameter_description'><option value=''>Select Data Type</option><option value='OCTET_STRING'>String</option><option value='INTEGER'>Integer</option><option value='INTEGER32'>Unsigned Integer</option><option value='IPADDRESS'>IP Address</option><option value='x'>Hex String</option></select></td><td><input type='text' class='expectedValue' name='expected_value'></td>");
newrow.append(newcells);
$("tbody.parameter_table").append(newrow);
} else {
let name = $(this).parent("td").next("td").next("td").text();
let newname = name.split('.').join('');
console.log("newname: " + newname)
$("#addParamTable").find("#" + newname).closest("tr").remove();
$("#all").prop("checked", false);
}
})
You can do it like this. Note that initially the fields are not disabled because no value is selected at the Execution Type select field. Maybe you want to make this more clear by adding an initial option with the text "Select Type" to the select field like you have it for the select for Data Type.
$("#all").on("click", function() {
if ($(this).is(":checked")) {
let boxes = $("#paramTable input[type='checkbox']").not(this).not(":checked");
boxes.each(function() {
$(this).click();
});
} else {
let boxes = $("#paramTable input[type='checkbox']:checked").not(this);
boxes.each(function() {
$(this).click();
});
}
});
$("#paramTable input[type='checkbox']:not(#all)").on("click", function() {
if ($(this).is(":checked")) {
let name = $(this).parent("td").next("td").next("td").text().trim();
let newname = name.split('.').join('');
let newrow = $("<tr>");
let newcell = $("<td> ");
let newSel = $("<select class='ExeType' name='ExeTypeValue'><option value='getData'>Get</option><option value='SetData'>Set</option></select>")
newcell.append(newSel);
newrow.append(newSel);
let newcell1 = $("<td> ");
let newinput = $("<input type='text' class='parameterName' name='" + newname + "' id='" + newname + "' value='" + name + "'/>");
newcell1.append(newinput);
newrow.append(newcell1);
let newcells = $("<td><select class='parameterDscription' name='parameter_description'><option value=''>Select Data Type</option><option value='OCTET_STRING'>String</option><option value='INTEGER'>Integer</option><option value='INTEGER32'>Unsigned Integer</option><option value='IPADDRESS'>IP Address</option><option value='x'>Hex String</option></select></td><td><input type='text' class='expectedValue' name='expected_value'></td>");
newrow.append(newcells);
$("tbody.parameter_table").append(newrow);
} else {
let name = $(this).parent("td").next("td").next("td").text();
let newname = name.split('.').join('');
console.log("newname: " + newname)
$("#addParamTable").find("#" + newname).closest("tr").remove();
$("#all").prop("checked", false);
}
})
$(document).on("change", ".ExeType", function() {
let type = $(this).val();
if (type === "getData") {
$(this).closest("tr").find(".parameterDscription").attr("disabled", "disabled");
$(this).closest("tr").find(".expectedValue").attr("disabled", "disabled");
} else {
$(this).closest("tr").find(".parameterDscription").removeAttr("disabled");
$(this).closest("tr").find(".expectedValue").removeAttr("disabled");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="paramTable">
<tr>
<td><input type="checkbox" id="all" /></td>
<td>Select all</td>
<td></td>
</tr>
<tr>
<td><input type="checkbox" /></td>
<td>Testing 1</td>
<td>1.2.3.4.5</td>
</tr>
<tr>
<td><input type="checkbox" /></td>
<td>Testing 2</td>
<td>.1.3.4.5.8</td>
</tr>
</table>
<div class="tab-content">
<div id="protocol" class="tab-pane fade in active">
<div class="span3 border-0" style="overflow: scroll">
<table id="addParamTable" class="table table-bordered">
<thead>
<tr class="info">
<th>Excution Type</th>
<th>Parameter Name</th>
<th>Data Type</th>
<th>Expected Set Value</th>
</tr>
</thead>
<tbody class="parameter_table">
</tbody>
</table>
</div>
</div>
</div>

how to use javascript or jquery create table fast

I want to create a table by click a button,and i need to save the table to the database .this is the code to create table but i think this is so long,how can i create it fast?
var div = document.createElement("div");
var table1 = document.createElement("table");
var table2 =document.createElement("table");
var thead = document.createElement("thead");
var th1 = document.createElement("th");
var th2 = document.createElement("th");
var th3 = document.createElement("th");
th1.innerHTML="Count";
th2.innerHTML="Date";
th3.innerHTML="Price";
document.body.appendChild(div);
div.appendChild(table1);
div.appendChild(table2);
table2.appendChild(thead);
thead.appendChild(th1);
thead.appendChild(th2);
thead.appendChild(th3);
If the code is too long then I recommend creating an html table structure inside a div that is not displayed. Then when the user clicks the button then you could
Display the table that is hidden.
Clone the table and append it to something (if you expect to create the table multiple times)
Your code would then look like so (cloning wise):
jQuery:
$('#myButton').on('click', function(){
$(document.body).append($('original').clone());
});
Javascript:
document.getElementById('myButton').onclick = function(){
document.body.appendChild(document.getElementById('original').cloneNode());
}
And here is the html table you can have hidden.
<div style="display: none;">
<table id="original">
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
</table>
</div>
This reduces greatly your javascript code.
If you want to make some enhancement than you can use precompiled template like muchtache.js :
<table>
<tr>
<th> Count </th>
<th> Date </th>
<th> Price </th>
</tr>
{{#jsonObject}}
<tr>
<td>{{Count1}}</td>
<td>{{Date1}}</td>
<td>{{Price1}}</td>
</tr>
{{/jsonObject}}
</table>
in javascript, you can write your javascript jsonobject as :
jsonobject : [{
count1 : 1,
date1 : 12/12/2012,
price1 : 100
},
{
count1 : 2,
date1 : 12/12/2013,
price1 : 200
}
]
for full muchtache example visit Json Object into Mustache.js Table
The following function might help:
function html2dom (html) {
var div = document.createElement('div');
div.innerHTML = html;
return div.removeChild(div.firstChild);
}
Here is how to use it:
document.body.appendChild(html2dom(''
+ '<div>'
+ '<table></table>'
+ '<table>'
+ '<thead>'
+ '<th>Count</th>'
+ '<th>Date</th>'
+ '<th>Price</th>'
+ '</thead>'
+ '</table>'
+ '</div>'
));
Live demo:
document.body.appendChild(html2dom(''
+ '<div>'
+ '<p>Paragraph.</p>'
+ '<ul>'
+ '<li>Item 1.</li>'
+ '<li>Item 2.</li>'
+ '<li>Item 3.</li>'
+ '</ul>'
+ '</div>'
));
function html2dom (html) {
var div = document.createElement('div');
div.innerHTML = html;
return div.removeChild(div.firstChild);
}

How to read HTML <table> and sort the table content?

I have a html table with three columns [Title, Category, Sub-Category] and multiple rows . And I want to read the entire table content and make it categorized as below output.
My <html> table content is like this.
Title Category Sub
T1 C1 S1
T2 C2 S2
T3 C2 S3
T3 C1 S1
T2 C1 S3
T1 C2 S3
Here is the output format what I really need. I just want to print the above html table content in the below out put format.
T1 :
C1 : S1
C2 : S3
T2 :
C2 : S2
C1 : S3
T3 :
C2 : S3
C1 : S3
[Title]
[Category] :[Sub-Category]
Please help me.
Assuming the table has this code:
<table>
<thead>
<tr>
<th>Title</th>
<th>Category</th>
<th>Sub</th>
</tr>
</thead>
<tbody>
<tr>
<th>T1</th>
<td>C1</td>
<td>S1</td>
</tr>
<tr>
<th>T2</th>
<td>C2</td>
<td>S2</td>
</tr>
<tr>
<th>T3</th>
<td>C2</td>
<td>S3</td>
</tr>
<tr>
<th>T3</th>
<td>C1</td>
<td>S1</td>
</tr>
<tr>
<th>T2</th>
<td>C1</td>
<td>S3</td>
</tr>
<tr>
<th>T1</th>
<td>C2</td>
<td>S3</td>
</tr>
</tbody>
</table>
We can use jQuery to get output like this:
$(document).ready(function(){
$("table").hide();
$("body").append("<textarea></textarea>");
var s = "";
$("tbody tr").each(function(){
s += $(this).find("th").html() + ":\n";
s += $(this).find("td:nth-child(2)").html() + ": " + $(this).find("td:nth-child(3)").html() + "\n\n";
});
$("textarea").val(s);
});
Fiddle: http://jsfiddle.net/praveenscience/9ueervw4/
The below code, you get a JavaScript object which is associative!
$(document).ready(function(){
$("table").hide();
$("body").append("<textarea></textarea>");
var s = {};
$("tbody tr").each(function(){
if (!s[$(this).find("th").html()])
s[$(this).find("th").html()] = [];
s[$(this).find("th").html()].push($(this).find("td:nth-child(2)").html() + ": " + $(this).find("td:nth-child(3)").html());
});
});
Try using associative arrays in javascript/jQuery: DEMO
var tableRowArray = $('table tr');
var titleArray = [];
var mainArray = {};
// build an associative array of the values int he table
tableRowArray.each(function(){
if($(this).children('th').length == 0) {
var tempTitle = $(this).children('td').eq(0).text();
if(mainArray[tempTitle]){
mainArray[tempTitle][$(this).children('td').eq(1).text()] = $(this).children('td').eq(2).text();
}
else {
titleArray.push(tempTitle);
mainArray[tempTitle] = {};
mainArray[tempTitle][$(this).children('td').eq(1).text()] = $(this).children('td').eq(2).text();
}
}
});
// print the formatted associative array to the page
$('body').append("<p></p>");
var formattedString = "";
$.each(titleArray, function(index, value){
formattedString += "<b>" + value + " : </b><br/>";
for(var key in mainArray[value]) {
formattedString += " " + key + " : " + mainArray[value][key] + "<br/>";
}
});
$('p').html(formattedString);
Basically, we create an associative array from your table and then the next piece iterates through the array to print it in the format you specified (you may need to edit the set up of the array if you table structure varies from what I used the in JSfiddle).
The below example will give you the output you want.
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script language="javascript">
$(document).ready(function () {
var outputtemp = "<table>";
$("#tbl1 tr").not("tr th").each(function () {
outputtemp += "<tr>"
var i = 0;
$(this).find("td").each(function () {
if (i == 0)
outputtemp += "<td>" + $(this).text() + ":</td></tr><tr>";
else if (i == 1)
outputtemp += "<td></td><td>" + $(this).text() + ":</td>";
else
outputtemp += "<td>" + $(this).text() + "</td>";
i++;
});
outputtemp += "</tr>"
});
outputtemp += "</table>"
$(".output").html(outputtemp);
});
</script>
</head>
<body>
<table id="tbl1">
<tr>
<th>
Title
</th>
<th>
Category
</th>
<th>
Sub
</th>
</tr>
<tr>
<td>
T1
</td>
<td>
C1
</td>
<td>
S1
</td>
</tr>
<tr>
<td>
T2
</td>
<td>
C2
</td>
<td>
S2
</td>
</tr>
<tr>
<td>
T3
</td>
<td>
C3
</td>
<td>
S3
</td>
</tr>
</table>
<div class="output">
</div>
</body>
</html>
Get the data using getElementbyId and then you may apply any operation on that data when you have whole data in js variables.

Set Link in table cell with jQuery

I have a table with three td´s. In the third td I´d like to dynamically set a link in a with data from other two td cells.
I know, how to change the link, but every row get the link from the first row. Maybe a very simple solution, but I´m a little helpless
My Code so far:
HTML:
<table id="table">
<tbody>
<tr>
<td class="one">11</td>
<td class="two">12</td>
<td class="three"><a href='#'>13</a></td>
</tr>
<tr>
<td class="one">21</td>
<td class="two">22</td>
<td class="three">23</td>
</tr>
</tbody>
</table>
Script:
$(document).ready(function () {
var row = $('#table .three a').closest('tr');
var td = row.find('td');
var id1 = td.eq(0).text();
var id2 = td.eq(1).text();
$('#table .three a').attr("href", "test.html?" + id1 + "-" + id2);
});
Fiddle
You can use this:
$('#table .three a').each(function () {
var id1 = $(this).closest('tr').find('td:eq(0)').text();
var id2 = $(this).closest('tr').find('td:eq(1)').text();
$(this).prop("href", "test.html?" + id1 + "-" + id2);
});
jsFiddle example
change your javascript to this
$(document).ready(function () {
$('#table .three a').each(function(){
var row = $(this).closest('tr');
var td = row.find('td');
var id1 = td.eq(0).text();
var id2 = td.eq(1).text();
$(this).attr("href", "test.html?" + id1 + "-" + id2);
})
});
You need to use .each()
$('#table .three a').each(function (index) {
var row = $(this).closest('tr');
var td = row.find('td');
var id1 = td.eq(0).text();
var id2 = td.eq(1).text();
$(this).attr("href", "test.html?" + id1 + "-" + id2);
});
DEMO

Proper rows not getting colored

My rows are not getting colored properly"
Please have a look at my HTML output:
<table id="mytable" cellspacing="0" cellpadding="5">
<tbody>
<tr class="tableheader">
<th>Name</th>
<th>Code</th>
<th>Value</th>
<th>Bid</th>
<th>Offer</th>
</tr>
<tr class="rowoddcolor">
<td>Apple</td>
<td>APPL</td>
<td>111</td>
<td>112</td>
<td>110</td>
</tr>
<tr class="tablecontent">
<td>Microsoft</td>
<td>MSFT</td>
<td>78</td>
<td>70</td>
<td>75</td>
</tr>
<tr class="rowevencolor">
<td>Google</td>
<td>GOGL</td>
<td>101</td>
<td>98</td>
<td>102</td>
</tr>
<tr class="tablecontent">
<td>Nokia</td>
<td>NOK</td>
<td>10</td>
<td>8</td>
<td>9</td>
</tr>
<tr class="rowoddcolor">
<td>Samsung</td>
<td>SAMS</td>
<td>89</td>
<td>86</td>
<td>90</td>
</tr>
<tr class="tablecontent">
<td>IntelCorporation</td>
<td>INTC</td>
<td>111</td>
<td>112</td>
<td>110</td>
</tr>
</tbody>
</table>
Now only the 1st and 5th row getting colored? why not 3rd row?
updated code:
function tablerows(id){
if(document.getElementsByTagName){
var tableid = document.getElementById(id);
var rows = tableid.getElementsByClassName('tablecontent');
for(i = 0; i < rows.length; i++){
if(i % 2 == 0){
rows[i].className = "rowevencolor";
}else{
rows[i].className = "rowoddcolor";
}
}
}
}
$(document).ready(function() {
$.getJSON('table.json',function(data){
$('#mytable').empty();
var html = '';
html += '<tr class="tableheader"><th>Name</th><th>Code</th><th>Value</th><th>Bid</th><th>Offer</th></tr>';
for (var i=0, size=data.length; i<size;i++) {
html += '<tr class="tablecontent"><td class="name">'+ data[i].name+ '</td><td class="code">'+ data[i].code+ '</td><td class="value">'
+ data[i].value+ '</td><td class="bid">'
+data[i].bid+'</td><td class="offer">'+data[i].offer+'</td></tr>';
}
$('#mytable').append(html);
tablerows('mytable');
});
});
I am creating html through jquery consuming json. Table is getting created properly. Now through javascript, i am styling my alternate rows to different color and header should be in different color. This is my first question. Please see below my script:
function tablerows(id){
if(document.getElementsByTagName){
var tableid = document.getElementById(id);
var rows = tableid.getElementById("tablecontent");
for(i = 0; i < rows.length; i++){
if(i % 2 == 0){
rows[i].className = "rowevencolor";
}else{
rows[i].className = "rowoddcolor";
}
}
}
}
$(document).ready(function() {
$.getJSON('table.json',function(data){
$('#mytable').empty();
var html = '';
html += '<tr class="tableheader"><th>Name</th><th>Code</th><th>Value</th><th>Bid</th><th>Offer</th></tr>';
for (var i=0, size=data.length; i<size;i++) {
html += '<tr id="tablecontent"><td class="name">'+ data[i].name+ '</td><td class="code">'+ data[i].code+ '</td><td class="value">'
+ data[i].value+ '</td><td class="bid">'
+data[i].bid+'</td><td class="offer">'+data[i].offer+'</td></tr>';
}
$('#mytable').append(html);
});
$(function(){
tablerows('mytable');
});
});
But my rows are not getting styled. Please tell me where is the problem.
Below is css code as well:
.rowoddcolor{
background-color:#FFFFFF;
}
.rowevencolor{
background-color:#D3D3D3;
}
I believe the function "tablerows" is getting executed before the build of table. So put that code after the append method.
Example :
$(document).ready(function() {
$.getJSON('table.json',function(data){
// existing stuff
$('#mytable').append(html);
tablerows('mytable');
});
});
Also the easiest way add the color class on alternating would be :
$('#mytable tr:even').addClass("rowevencolor");
$('#mytable tr:odd').addClass("rowoddcolor");
A few things:
First, Element ID's should be unique. Do not give every tr the same id tablecontent.
After that's fixed, you can ditch the entire helper function tablerows() as it is redundant and that logic can be moved to where you are building the table, i.e.:
for (var i=0, size=data.length; i<size;i++) {
html += '<tr class="tablecontent row' + (i % 2 ? 'even' : 'odd') + 'color"><td class="name">'+ data[i].name+ '</td><td class="code">'+ data[i].code+ '</td><td class="value">'
+ data[i].value+ '</td><td class="bid">'
+ data[i].bid+'</td><td class="offer">'+data[i].offer+'</td></tr>';
}
Or simply use psuedo-selectors in your CSS as recommended by Kundan
The reason why your code is not highlighting table row #3 is because the result of getElementsByClassName is a NodeList, not an Array.
You will thus need to convert the NodeList to an Array before using the indexing operator for random access.
e.g.
var rowsList = tableid.getElementsByClassName('tablecontent');
var rows = Array.prototype.slice.call(rowsList);
for (i = 0; i < rows.length; i++)
// ...
Here is a working fiddle
However, as per Kundan's answer, it seems strange why you wouldn't use a jQuery solution, as it is much less work. jQuery fiddle here

Categories