I have a HTML table in which there are child rows , I want to make those child rows column clickable to perform particular action.
I have parent rows and when I click on those rows, child rows are being shown, in which there is a column col2 , on which when I click it should perform some action for each child rows column.
I want col2 of child row to be clickable to show some more information using JavaScript and HTML. I don't know, but on click function(onclick('col2')) something like that can be helpfull or not??
var $container = $("#container");
var $row = $("#container table tbody tr");
// Loop through items in JSON data..
var $button = $("<button>" + 'abc' + "</button>");
$container.prepend($button);
var table = $("<table>");
table.append($("<tr><th>col1</th><th>col2</th></tr>"));
// Button click handler..
$button.on("click", function() {
for (var i = 0; i < 2; i++) {
// Replace row HTML..
//parent row
var row = $('<tr class="parent_row" ><td>' + 'data' + '</td>' + +'<td>' + "" + '</td></tr>');
table.append(row);
for (var j = 0; j < 2; j++) {
//child row
var row = $('<tr style="display: none"><td>' + "" + '</td>' + '<td>' + 'data' + '</td></tr>');
table.append(row);
}
}
$("#table").html(table);
$('.parent_row').click(function() {
$(this).nextUntil(".parent_row").toggle();
})
// Show table if it's not already visible..
});
table {
margin-top: 20px;
border: 1px solid silver;
width: 500px;
}
th {
text-align: left;
}
button {
margin-left: 15px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
<div id="table">
</div>
</div>
To catch clicks on any column in a table, simply add a click listener to all cells in that column:
const column2cells = document.querySelectorAll('#table tr>*:nth-child(2)');
for (const cell of column2cells) {
cell.addEventListener('click', function(event) {
console.log(`You clicked cell [${cell.cellIndex}, ${cell.parentElement.rowIndex}] with content "${cell.textContent}"`);
})
}
<table id="table">
<tr>
<th>Col 1</th>
<th>Col 2</th>
</tr>
<tr>
<td>Col 1</td>
<td>Col 2</td>
</tr>
<tr>
<td>Col 1</td>
<td>Col 2</td>
</tr>
</table>
As a note for the logging output: Remember cellIndex and rowIndex start at 0, not at 1.
var $container = $("#container");
var $row = $("#container table tbody tr");
// Loop through items in JSON data..
var $button = $("<button>" + 'abc' + "</button>");
$container.prepend($button);
var table = $("<table>");
table.append($("<tr><th>col1</th><th>col2</th></tr>"));
// Button click handler..
$button.on("click", function() {
for (var i = 0; i < 2; i++) {
// Replace row HTML..
//parent row
var row = $('<tr class="parent_row" ><td>' + 'data' + '</td>' + +'<td>' + "" + '</td></tr>');
table.append(row);
for (var j = 0; j < 2; j++) {
//child row
var row = $('<tr style="display: none"><td>' + "" + '</td></tr>');
$('<td>data</td>')
.on('click', function() { alert('some action') })
.appendTo(row);
table.append(row);
}
}
$("#table").html(table);
$('.parent_row').click(function() {
$(this).nextUntil(".parent_row").toggle();
})
// Show table if it's not already visible..
});
table {
margin-top: 20px;
border: 1px solid silver;
width: 500px;
}
th {
text-align: left;
}
button {
margin-left: 15px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
<div id="table">
</div>
</div>
You could give a specific class name to each <td> in col2 when you are creating them, and then using a regular onclick event based on that class name.
So:
var row = $('<tr class="parent_row" ><td>' + 'data' + '</td>' + +'<td class="col2">' + "" + '</td></tr>');
And then:
$(".col2").on("click", function() {
//whatever you want to do here
});
Related
I have a table that is filled dynamically with a csv file. I created a table that inside itself has dropdowns in some columns.
What I want to do now is to check if a value exists in the cell where the dropdown is supposed to be, if so to check if it exists in the dropdownlist if yes then set this as selected in dropdown list otherwise selected is at default value and the cell gets red margine around.
Here is a jsFiddle with an example as how my code currently looks like:
https://jsfiddle.net/r236uy5k/
EDIT : I corrected my jsfiddle:
https://jsfiddle.net/kcau7jhd/
$(function(){
var firstDDM = ['aaa','bbb','ccc','ddd'];
var firstshortcut = ['a','b','c','d'];
var option = "",
select = "";
for(var i=0; i<firstDDM.length;i++){
option += '<option value="'+ firstshortcut[i] + '">' + firstDDM[i] + '</option>';
}
select = '<select class="firstDDM" type="firstDDM">' + option + '</select>';
$("tr").each(function() {
$(this).find("td:eq(3)").append(select);
});
});
$(function(){
var secondDDM = ['Default','AAA','BBB','B1','C'];
var secondshortcut = ['Default','a','b','b1','c'];
var option = "",
select = "";
for(var i=0; i<secondDDM.length;i++){
option += '<option value="'+ secondshortcut[i] + '">' + secondDDM[i] + '</option>';
}
select = '<select class="secondDDM" type="secondDDM">' + option + '</select>';
$("tr").each(function() {
$(this).find("td:eq(5)").append(select);
});
});
$("#addRow").click(function(){
$("#my_id").each(function(){
var tds='<tr>';
jQuery.each($('tr:last th', this), function(){
tds += '<th>' +'<input type="checkbox" name="record" tittle="Delete this row"></input>' + '</th>';
});
jQuery.each($('tr:last td', this), function(){
if($('select',this).length){
tds+= '<td>' + $(this).html() + '</td>';
}else{
tds+= '<td></td>';
}
});
tds+= '</tr>';
$('tbody',this).append(tds);
$('#my_id tbody tr:last').attr("contentEditable", true);
});
});
//for the columns that need to be imported with dropdowns create editable option - temporarlly
$(function() {
$("tr").each(function() {
$(this).find("td:eq(3), td:eq(4),td:eq(5)").attr("contentEditable", true);
});
});
//Find and remove selected table rows
$('#delete-row').click(function(){
var r = confirm('Are you sure you want to delete them all?');
$("tbody").find('input[name="record"]').each(function(){
if($(this).is(":checked")){
if(r == true){
$(this).parents("tr").remove();
}else{
return false;
}
}
});
});
table {
border-collapse: collapse;
border: 1px black solid;
font: 12px sans-serif;
width: 100%;
table-layout:auto;
}
td {
border: 1px black solid;
text-align: left;
padding: 2px;
}
thead:hover{
text-decoration: none !important;
}
thead tr:first-child{
color:white;
text-align: center;
background-color: #5bc0de;
padding: 10px;
}
tr:nth-child(even){
background-color: #f2f2f2
}
tr:hover{
background-color: #5bc0de;
}
button{
display: inline;
padding: 50px;
}
input button{
display: inline;
}
.dropbtn{
background-color: blue;
}
.table-responsive {
overflow-y: auto;
height: 800px;
}
.table-responsive table {
border-collapse: collapse;
width: 100%;
}
.table-responsive thead th{
position: sticky;
top: 0;
background-color: #5bc0de;
padding: 2px;
}
::-webkit-scrollbar {
width: 12px;
}
::-webkit-scrollbar-thumb {
background-color: darkgrey;
outline: 1px solid slategrey;
}
.myButtons{
display: inline;
padding: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<head>
<title>Filtered CSV File</title>
</head>
<body>
<h1>
Filtered CSV FIle
</h1>
<br/>
<br/>
<div class="myButtons">
<input type="button" value="Add new row" class="btn btn-info" id="addRow">
<input type="button" value="Delete rows" id="delete-row" class="btn btn-info">
</div>
<br/>
<div class="table-responsive">
<table class="dataframe my_class" id="my_id">
<thead>
<tr style="text-align:right;">
<th> </th>
<th>col1</th>
<th>col2</th>
<th>col3</th>
<th>col4</th>
<th>col5</th>
<th>col6</th>
<th>col7</th>
<th>col8</th>
</tr>
</thead>
<tbody>
<tr>
<th>1</th>
<td>row1</td>
<td>row1</td>
<td>row1</td>
<td></td>
<td>row1</td>
<td>B1</td>
<td>row1</td>
<td>row1</td>
</tr>
<tr>
<th>2</th>
<td>row2</td>
<td>row2</td>
<td>row2</td>
<td></td>
<td>row2</td>
<td>AAA</td>
<td>row2</td>
<td>row2</td>
</tr>
<tr>
<th>3</th>
<td>row3</td>
<td>row3</td>
<td>row3</td>
<td></td>
<td>row3</td>
<td>C</td>
<td>row3</td>
<td>row3</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
You can edit the select text you are entering. Following are the things which I think you want to achieve:
Identify if the dropdown has a certain value and preselect them if possible.
If the dropdown does not have correct value for pre selection then mark them as error field.
If the above mentioned points are incorrect please let me know i will make the relevant changes which are required.
I have added a condition check if (firstshortcut[i] == $(this).find("td:eq(3)")[0].innerHTML) you can replace it with any condition that you want.
Replace the following jquery snippets
$("tr").each(function () {
var option = "",
select = "",
classObject = '',
isSelected = false;
if($(this).find("td:eq(3)")[0]){
for (var i = 0; i < firstDDM.length; i++) {
if (firstshortcut[i] == $(this).find("td:eq(3)")[0].innerHTML) {
option += '<option selected="selected" value="' + firstshortcut[i] + '">' + firstDDM[i] + '</option>';
isSelected = true;
}
else
option += '<option value="' + firstshortcut[i] + '">' + firstDDM[i] + '</option>';
}
classObject = !isSelected ? 'errorDropDown' : '';
select = '<select class="firstDDM' + ' ' + classObject + '" type="firstDDM">' + option + '</select>'
$(this).find("td:eq(3)").append(select);
}
});
Add this class to the css file:
.errorDropDown {border: 1px solid red;}
The code basically edit a table cell.
I want to use the not() method so that everytime I click outside the temporary input created I replace it with a table cell. I guess the code run in a block and doesn't detect any input with an id of "replace" so how can I fix that ?
Also I want to store the element (th or td) that fire the first event(dblclick) so that I can use it to replace the input with the right type of cell but it seems to only stores the element that first triggers the event and I don't really understand why.
Full code here
$(function () {
$(document).on("dblclick", "th, td", function (event) {
var cellText = $(this).text();
$(this).replaceWith("<input type='text' id='replace' value='" + cellText + "'>");
var $typeCell = $(event.currentTarget); // Store element which trigger the event
$("body").not("#replace").on("click", function () { // .not() method
cellText = $("#replace").val();
if ($typeCell.is("th")) {
$("#replace").replaceWith("<th scope='col'>" + cellText + "</th>");
}
else {
$("#replace").replaceWith("<td>" + cellText + "</td>");
}
});
});
});
I have modified HTML and JavaScript to avoid any possible errors. The correct practice is to wrap all th's in a thead and all td's in tbody.
$(document).on("dblclick", "th, td", function(event) {
var cellText = $(this).text();
$(this).replaceWith("<input type='text' id='replace' value='" + cellText + "'>");
});
$("body").on("click", function() {
if (event.target.id != 'replace' && $('#replace').length != 0) {
var cellText = $("#replace").val();
if ($('#replace').parents().is('thead'))
$("#replace").replaceWith("<th scope='col'>" + cellText + "</th>");
else
$("#replace").replaceWith("<td>" + cellText + "</td>");
}
});
table {
border-collapse: collapse;
margin: 20px;
min-width: 100px;
}
table,
th,
td {
border: 1px solid grey;
padding: 4px;
}
th {
background: springgreen;
}
tr:nth-child(odd) {
background: rgba(0, 255, 127, 0.3);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<table>
<thead>
<tr>
<th scope="col">Uno</th>
<th scope="col">Dos</th>
<th scope="col">Tres</th>
</tr>
</thead>
<tbody>
<tr>
<td>Data1</td>
<td>Data2</td>
<td>Data3</td>
</tr>
<tr>
<td>Data4</td>
<td>Data5</td>
<td>Data6</td>
</tr>
</tbody>
</table>
</div>
I've Add the event click to my dynamic table but it doesnt work.
$("#gridVille").append('<table id="idTableVille" class="table table-striped table-hover">');
$("#idTableVille").append('<thead>');
$("#idTableVille thead").append('<tr><th>Code commune</th><th>Libellé</th></tr>');
$("#idTableVille").append('</thead>');
$("#idTableVille").append('<tbody>');
for (i = 0; i < liste.length; i++) {
$("#idTableVille tbody").append('<tr id="' +liste[i].id+ '">');
$('#idTableVille tbody').append('<td scope="row" class="idCommune">' + liste[i].id+ '</td>');
$('#idTableVille tbody').append('<td class="libelleCommune">' + liste[i].libelle+ '</td>');
$("#idTableVille tbody").append('</tr>');
}
$("#idTableVille").append('</tbody>');
$("#gridVille").append('</table>');
$('#idTableVille tr').click(function () {
var id = $(this).find('td:eq(0)').text();
var libelle = $(this).find('td:eq(1)').text();
alert(id + ' ' + libelle);
});
this code is added after populating the table.
The scenario is :
I Open the modal (bootstrap modal)
I populate the table
I click to any row of table for getting the values of columns
You are appending the <tr> element to the <tbody> and then also appending every <td> to the <tbody> instead of the newly generated row, so instead of a regular table structure:
<table>
<tbody>
<tr id="something">
<td>Something</td>
<td>Hello!</td>
</tr>
</tbody>
</table>
You are getting this:
<table>
<tbody>
<tr id="something"></tr>
<td>Something</td>
<td>Hello!</td>
</tbody>
</table>
If you change the code inside the for loop it should get fixed:
for (i = 0; i < liste.length; i++) {
$("#idTableVille tbody").append('<tr id="' +liste[i].id+ '">');
$('#idTableVille tbody tr#' + liste[i].id).append('<td scope="row" class="idCommune">' + liste[i].id+ '</td>');
$('#idTableVille tbody tr#' + liste[i].id).append('<td class="libelleCommune">' + liste[i].libelle+ '</td>');
}
As you can see, I'm appending the elements to the newly created row, using the id to select it.
You can see it working here:
https://jsbin.com/yojajisuca/edit?html,js,output
i currently have a code that can append the result into the html page.
This is the append code.
function casefeed(response) {
var arr = JSON.parse(response);
var i;
for(i = 0; i < arr.length; i++) {
$("#viewcase").append("<td><img src='" + serverURL()
+ "/images/"+ arr[i].Case_Pic + "' height='100'>"
+ "<td>" + arr[i].CaseTime + "</a></b></td>");
}
}
This is my table format.
<table class="tile-table">
<tbody id = "viewcase">
<tr>
<td>
<div class="tile" style="background-position: -0px -0px;"></div>
</td>
<td>
<div class="tile" style="background-position: px -0px;"></div>
</td>
<td>
<div class="tile" style="background-position: -200px -0px;"></div>
</td>
<td>
<div class="tile" style="background-position: -300px -0px;"></div>
</td>
</tr>
</tbody>
</table>
My current result is like this.
Is it possible to display the image into this format?
You can achieve this by adding nth-child(n). for sample i m considering the array as numbers from 1 to 9 . you can pass your url in the place of imageurl
$(function() {
function casefeed() {
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var i;
var imageurl = "http://feelgrafix.com/data/images/images-1.jpg";
for (i = 0; i < arr.length; i++) {
if (i % 3 == 0) {
$("#viewcase").append("<tr></tr>");
}
$("#viewcase:nth-child(n)").append("<td><img src='" + imageurl + "' >Time</td>");
}
}
casefeed();
});
img {
width: 200px;
height: 150px;
}
td {
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="tile-table">
<tbody id="viewcase">
</tbody>
</table>
You are appending td to tbody, you should append it to tr. Also, there are two closing tags without opening tags - </a></b>
This is what I suggest:
HTML
<table class="tile-table">
<tbody id = "viewcase">
</tbody>
</table>
Javascript
function casefeed(response) {
var arr = JSON.parse(response);
var i;
for(i = 0; i < arr.length; i++) {
if (i % 3 === 0)
$("#viewcase").append("tr"); // add new table row each 3 elements
$("#viewcase tr").last().append("<td><img src='" + serverURL()
+ "/images/"+ arr[i].Case_Pic + "' height='100'>"
+ "<td><p>" + arr[i].CaseTime + "</p></td>");
}
}
I have this table:
<table border="1">
<tr>
<td></td>
<td>Banana</td>
<td>Orange</td>
<td>Plum</td>
</tr>
<tr>
<td>Banana</td>
<td>1:1</td>
<td>1:2</td>
<td>1:3</td>
</tr>
<tr>
<td>Orange</td>
<td>2:1</td>
<td>1:1</td>
<td>1,5:1</td>
</tr>
<tr>
<td>Plum</td>
<td>1:3</td>
<td>2:1</td>
<td>1:1</td>
</tr>
and CSS:
td {
height:60px;
width:60px;
text-align:center;
}
td:hover{
background-color:red;
}
What I want to do, is when I for example point my mouse on 1:3 table cell, it should highlight together with Banana and Plum cells.
Any easy way to do it?
Here's fiddle:
http://jsfiddle.net/CZEJT/
If you dont mind a bit of Javascript in there to ensure compatibility, take a look at this JSFiddle
HTML:
<table>
<tr>
<th></th><th>50kg</th><th>55kg</th><th>60kg</th><th>65kg</th><th>70kg</th>
</tr>
<tr>
<th>160cm</th><td>20</td><td>21</td><td>23</td><td>25</td><td>27</td>
</tr>
<tr>
<th>165cm</th><td>18</td><td>20</td><td>22</td><td>24</td><td>26</td>
</tr>
<tr>
<th>170cm</th><td>17</td><td>19</td><td>21</td><td>23</td><td>25</td>
</tr>
<tr>
<th>175cm</th><td>16</td><td>18</td><td>20</td><td>22</td><td>24</td>
</tr>
</table>
CSS:
table {
border-spacing: 0;
border-collapse: collapse;
overflow: hidden;
z-index: 1;
}
td, th, .ff-fix {
cursor: pointer;
padding: 10px;
position: relative;
}
td:hover::after,
.ff-fix:hover::after {
background-color: #ffa;
content: '\00a0';
height: 10000px;
left: 0;
position: absolute;
top: -5000px;
width: 100%;
z-index: -1;
}
tr:hover{
background-color: #ffa;
}
}
JS:
function firefoxFix() {
if ( /firefox/.test( window.navigator.userAgent.toLowerCase() ) ) {
var tds = document.getElementsByTagName( 'td' );
for( var index = 0; index < tds.length; index++ ) {
tds[index].innerHTML = '<div class="ff-fix">' + tds[index].innerHTML + '</div>';
};
var style = '<style>'
+ 'td { padding: 0 !important; }'
+ 'td:hover::before, td:hover::after { background-color: transparent !important; }'
+ '</style>';
document.head.insertAdjacentHTML( 'beforeEnd', style );
};
};
firefoxFix();
below is an example from one of my sites (css):
/*when hover over shape 5 dim shape 5*/
#shape5{
opacity:1.0;
filter:alpha(opacity=100);}
#shape5:hover{
opacity:0.4;
filter:alpha(opacity=40);}
/*When hoverover text5 dim shape 5!*/
#text5:hover + #shape5{opacity:0.4;
filter:alpha(opacity=40);}
Hope that helps!!
Oh Also view: How to affect other elements when a div is hovered
would you like something like this?
unfortunately it would be necessary some javascript
HTML
<table border="1">
<tr>
<td></td>
<td id='1'>Banana</td>
<td id='2'>Orange</td>
<td id='3'>Plum</td>
</tr>
<tr>
<td>Banana</td>
<td class='o1'>1:1</td>
<td class='o2'>1:2</td>
<td class='o3'>1:3</td>
</tr>
<tr>
<td>Orange</td>
<td class='o1'>2:1</td>
<td class='o2'>1:1</td>
<td class='o3'>1,5:1</td>
</tr>
<tr>
<td>Plum</td>
<td class='o1'>1:3</td>
<td class='o2'>2:1</td>
<td class='o3'>1:1</td>
</tr>
</table>
JAVASCRIPT
var cells1 = $('.o1');
cells1.on('mouseover', function(){
$($(this).parent().children()[0]).css({background: '#ddd'})
$('#1').css({background: '#ddd'})
})
cells1.on('mouseout', function(){
$($(this).parent().children()[0]).css({background: 'none'})
$('#1').css({background: 'none'})
})
var cells2 = $('.o2');
cells2.on('mouseover', function(){
$($(this).parent().children()[0]).css({background: '#ddd'})
$('#2').css({background: '#ddd'})
})
cells2.on('mouseout', function(){
$($(this).parent().children()[0]).css({background: 'none'})
$('#2').css({background: 'none'})
})
var cells3 = $('.o3');
cells3.on('mouseover', function(){
$($(this).parent().children()[0]).css({background: '#ddd'})
$('#3').css({background: '#ddd'})
})
cells3.on('mouseout', function(){
$($(this).parent().children()[0]).css({background: 'none'})
$('#3').css({background: 'none'})
})
CSS
td {
height:60px;
width:60px;
text-align:center;
}
td:hover{
background-color:red;
}
Try this:
Fiddle
Without changing your html structure or adding any third party library:
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function () {
var tds = document.getElementsByTagName('td');
for (var i = 0; i < tds.length; i++) {
var elem = document.getElementsByTagName('td')[i];
elem.addEventListener('mouseover', function () {
var text = this.innerHTML;
for (var j = 0; j < tds.length; j++) {
var elem2 = document.getElementsByTagName('td')[j];
if (elem2.innerHTML == text) {
elem2.style.background = 'red';
}
}
}, false);
elem.addEventListener('mouseout', function () {
for (var j = 0; j < tds.length; j++) {
var elem2 = document.getElementsByTagName('td')[j];
var text = this.innerHTML;
if (elem2.innerHTML == text) {
elem2.style.background = 'none';
}
}
}, false);
}
}, false);
</script>
I apologise that my answer is only in pseudo code, however I would approach this problem by using javascript (most possibly Jquery). I hope this makes sense...
<table id="tbl"> - so I would give the table an ID
<td onHover="changeHeaderColummns(this)"></td> - then on each of the columns have a jsMethod that fires.
<script>
changeHeaderColumsn(col)
{
var colIndex = col.Index; //get the current column index
var row = GetHeaderRow(); // get the header row
highLightColumn(row, colIndex); //change the colour of the cell
//with the same index in the header
row = getCurrentRow(col.RowIndex); //now get the current row
highlightColumn(row, 0); //change the colour of the cell
//with the index of 0
}
getHeaderRow()
{
return getRow(0);
}
getRow(rowIndex)
{
var table = document.getElementByID("tbl);
return table.rows[rowIndex];
}
highlightColumn(row, colIndex)
{
row[colIndex].style.backgroundcolor = "red";
}
for highlight columns you must use js like this jsfiddler. It's work with jQuery ;)
With code
Using jquery
fiddle: http://jsfiddle.net/itsmikem/CZEJT/12/
Option 1: highlights the cell and just the named fruit cells
$("td").on({
"mouseenter":function(){
$(this).closest("tr").find("td:first-child").css("background","#f99");
var col = $(this).index();
$(this).closest("table").find("tr:first-child").find(String("td:nth-child(" + (col + 1) + ")")).css("background","#f99");
$(this).css("background","#f00");
},
"mouseleave":function(){
$(this).closest("table").find("td,tr").css("background","none");
}
});
Option 2: highlights entire rows and columns that intersect the hovered cell
$("td").on({
"mouseenter": function () {
$(this).closest("tr").css("background", "#f99");
var col = $(this).index();
var myTable = $(this).closest("table");
var rows = $(myTable).find("tr");
$(rows).each(function (ind, elem) {
var sel = String("td:nth-child(" + (col + 1) + ")");
$(this).find(sel).css("background", "#f99");
});
$(this).css("background", "#f00");
},
"mouseleave": function () {
$(this).closest("table").find("td,tr").css("background", "none");
}
});