Apply css styles in table created in Javascript (JQuery Mobile) - javascript

I have a table that is created dynamically using PHP and Javascript. Now, I'm trying to styling the last one <tr> to add a padding and border, but it doesn't work.
How can I proceed? I need call some element like trigger('create') or others?
Part of my code:
$.ajax ( {
beforeSend: function() { $.mobile.showPageLoadingMsg(); }, //Show spinner
complete: function() { $.mobile.hidePageLoadingMsg() }, //Hide spinner
url: "http://www.someweb.com/somePHP.php",
dataType: "json",
success: function (data, textStatus, jqXHR) {
for(var i = 0; i< data[1].length;i++){
table += "<tr><td>"+data[1][i].mon_da+"</td>";
table += "<td>"+Number(data[1][i].mon_qu).toFixed(2)+"€</td>";
table += "<td>"+data[1][i].mon_con+"</td></tr>";
}
table += "<tr style='border:1px solid;padding-top:20px;'><td colspan='2'><b>Disp:</b></td><td><b>"+Number(data[0].usr_to).toFixed(2)+"€</b></td></tr>";
document.getElementById("tableMo").innerHTML = table;
}
});

You can't apply styles to <tr>s like that.
You can try applying them to the <td>s instead.
I would personally prefer to add a class to the tr and handle the styles externally to JS in a CSS file.
jsFiddle
HTML
<tr class="stylish">
<td colspan='2'><b>Disp:</b></td>
<td><b>"+Number(data[0].usr_to).toFixed(2)+"€</b></td>
</tr>
CSS
.stylish td {
border:1px solid #000;
padding-top:20px;
}
.stylish td:first-child {
border-right:0;
}
.stylish td:last-child {
border-left:0;
}

You can get the table element by id and then add CSS style property with javascript:
for example:
document.getElementById("tableMo").style.border = "1px solid black";
document.getElementById("tableMo").style.padding = "10px";
Check out some DOM style tutorial, it might help you
http://www.w3schools.com/jsref/dom_obj_style.asp

One way of doing this is to add a class to your tr tags like so:
table += "<tr class='rowStyle'><td>"+data[1][i].mon_da+"</td>";
now you can style the rows,
or if you want to style the table itself, you can use jquery to get the parent of the row like so:
var obj = $('.rowStyle').closest('table');
and just give it an ID:
$(obj).attr('id','tableID');
Now just style it.
Although this is a lengthy method of doing it.
Hope this helps :)

You can do that using jquery css selector

Related

Changing CSS styling of individual columns in a Javascript-generated table

I have created a table to display JSON data via a for loop in a function. Because I have created the table this way, it has no ID/Class.
I have hidden the last three columns of the table in CSS via the following method, where (n) is the column number:
#divIdName table tr td:nth-child(n) {
display: none; }
#divIdName table th:nth-child(n) {
display: none; }
I am trying to display them via three javascript functions, using queryselector but directly coping the CSS i.e.
function showColumnN () {
if (ArrayName.indexOf("StringName")>-1) {
var colNd = document.querySelector("td:nth-child(n)");
var colNh = document.querySelector("th:nth-child(n)");
colNd.style.display = "block";
colNh.style.display = "block"; }
However only one of the hidden columns is displayed, and it contains just the three headings (one on top of another) and first row data (one on top of another) from each of the three.
Does anyone know where I'm going wrong and how I can get the full columns to display?
EDIT: I omitted that there was a conditional in the showColumnN function, to check whether a particular string is in a particular array and proceed with the column unveiling if this were so.
However only one of the hidden columns is displayed
That's because you've only selected the first td and th matching those selectors, but there are (presumably) multiple tds that match (one per row).
To keep going the way you're going (but don't, keep reading), you'd need to loop through those:
function showColumnN(n) {
showAll(document.querySelectorAll("td:nth-child(" + n + ")"));
showAll(document.querySelectorAll("th:nth-child(" + n + ")"));
}
function showAll(list) {
Array.prototype.forEach.call(list, function(element) {
element.style.display = "block";
});
}
However, I'd probably use a CSS solution instead where you could add classes to the table that would show those columns:
table.show1 tr > th:nth-child(1), table.show1 tr > td:nth-child(1) {
display: block;
}
table.show2 tr > th:nth-child(2), table.show2 tr > td:nth-child(2) {
display: block;
}
...and so on. Then showing column 2 (for instance) is:
document.querySelector("selector-for-the-table").classList.add("show2");
(Or better yet, use hideX classes that hide them, and only add those as appropriate. Then you don't have to do the block thing.)
Side note: The default display for td and th isn't block, it's table-cell.
You could do:
var table=document.getElementById("divIdName");
var rows=table.getElementsByTagName("tr");
rows.forEach((row)=>{
elems=row.getElementsByTagName("td");
for(i=0;i<4;i++){
elems[elems.length-4+i].style.display="block";
}
});
However T. J. Crowders answer is much shorter...

How to hide borders of empty table (HTML, Javascript)

I want to remove a HTML table completely from the screen and still be able to add rows to it later. I have the following code to remove all rows from a table (basically, it sets the inner HTML of the table to ""):
function removeAllRows() {
table = document.getElementById("myTable")
table.innerHTML = ""
}
However, when this function is called, the table isn't completely removed...there's a small speck on the table, which I believe has to do with the 1 pixel border of a table element.
I'd like to modify this function to completely remove the table from the screen, which would basically be hiding the table border when the table is empty.
Is there something that I could put in the style block to do this?
Right now, my style block looks like:
table, td {
border: 1px solid black;
border-collapse: separate;
empty-cells: hide;
}
empty-cells: hide; will hide the borders of empty cells, but not the border of the whole table if the whole table has no cells.
Is there any way to hide the border of an empty table?
fiddle
To just hide the table you can do this...
function removeAllRows() {
var table = document.getElementById("myTable")
// Checking that the table element exists before setting it to hidden to avoid nullreference exceptions.
if(!!table){table.hidden = true;}
}
You can alter the border programmatically. Add this line in removeAllRows()
table.style.border="0px";
Then in the addRow() method, add the border back:
table.style.border="1px solid black";
You can add a no border class to you table
function removeAllRows() {
table = document.getElementById("myTable")
table.innerHTML = ""
table.className = 'no-border';
}
And in you CSS file:
.no-border {
border: none;
}
Did not manage to solve it with CSS alone.
But you can either hide the table or just toggling the classlist property
if (table.children.length) {
table.classList.toggle('border') // whatever should replace default
}

How to change table cell background color using jquery

I want to change the background color of the cell based on its text contents using jquery.
Example:
For the second row in the "Exceeds" td, I want to change the background color to green because it has Exceeds as it's text...
<table>
<tr><td>Jedi Armor1</td><td>Needs</td></tr>
<tr><td>Jedi Armor2</td><td>Exceeds</td></tr>
</table>
I'm assuming you want to change the color of the cell and only the cell. If you want to change the color of it based on its text, use the contains() jQuery selector :
CSS :
.greenBg {
background: green;
}
jQuery :
$("td:contains('Exceeds')").addClass('greenBg');
jsFiddle Demo
Edit :
If you want to restrict this to the second column only, this would be more suited :
$("td:nth-child(2):contains('Exceeds')").addClass('greenBg');
In case someone would want to change the color of the whole column :
$("td:nth-child(2):contains('Exceeds')").closest('table').find('td:nth-child(2)').addClass('greenBg');
jsFiddle Demo
Native JS:
var td = document.getElementsByTagName("td");
var i = 0, tds = td.length;
for (i; i < tds; i++) {
if (td[i].innerHTML == "Exceeds") {
td[i].setAttribute("style", "background:green;");
}
}
Here's a jsfiddle to show: http://jsfiddle.net/vHvLh/
Update Following Question Clarification:
Demo Fiddle
To change the background color of one cell based on the value of another, you can use e.g:
$('table tr td:nth-child(4)').each(function () {
$(this).text() == 'Exceeds' && $(this).parent().find('td:nth-child(2)').css('background-color', 'green');
});
To change the background of a specific column:
$('table tr td:nth-child(2)').css('background-color', 'red');
However you should try to maintain the seperation of styles by using CSS, in which case you can accomplish this with:
table tr td:nth-child(2){
/* styles*/
}
Or..if you specifically need dynamic control, instead of allocating the style directly in jQuery, add a class:
$('table tr td:nth-child(2)').addClass('rowBackground');
Then in your CSS:
.rowBackground{
background-color:red;
}
You can use .eq() or :eq() selector:
$('table tr td:eq(3)').css('background-color','green');
or use .last() if the td that you want to change the color is always the last td:
$('table tr td').last().css('background-color','green')

Change colour of td in dynamic table generated in php

I'm creating a PHP script that will dynamically generate tr and td elements for a table. When the user clicks in a specific cell in the first column, an AJAX function executes to display additional content. This is working as it should, however, I'm having trouble with what should be simple styling. When the user clicks on a given cell, I want that row to change colour (works) until they click on another cell (doesn't work).
Since my PHP file is rather large, I'm only posting the relevant parts.
<?php
$myFiles = showMyAttrs();
foreach($myFiles as $myFile) {
echo("<tr class = 'gradeC' onClick = 'changeColour(this)' onchange = 'restoreColour(this)' >");
echo("<td onClick = 'sendCell(this)' ><img src = $msEx /></td>");
echo("<td>$myFile</td>");
echo("</tr>");
}
I've also tried using onblur instead of onchange but that gave the same result.
The Javascript functions:
function changeColour(z) {
z.style.backgroundColor = "#FFFFFF";
}
function restoreColour(y) {
y.style.backgroundColor = "#00FF00";
}
Before I also tried:
function changeColour(z) {
document.getElementsByTagName("tr").style.backgroundColor = "#00FF00";
z.style.backgroundColor = "#FFFFFF";
<!-- document.getElementsByTagName("td").style.backgroundColor = "#00FF00"; -->
}
function changeColour(z) {
z.style.backgroundColor = "#FFFFFF";
document.getElementsByTagName("tr").style.backgroundColor = "#00FF00";
}
$('tr').click(function() {
$('tr').css('backgroundColor', '#0F0');
$(this).css('backgroundColor', '#FFF');
});
With each of them (except the last), the colour does change to white, however, when the user clicks on any other row, the previous row doesn't return to green. I don't mind if this works with Javascript or JQuery, as long as it is compatible across browsers. Even a fancy CSS trick I'm fine with using.
You're on the right track. I think adding/removing a class would be a good way to go. You could try this:
jQuery
$('tr').on('click', function() {
$('tr').children('td').removeClass('active');
$(this).children('td').addClass('active');
});
CSS
.active { background-color: yellow; }
See jsFiddle
Try using a css class to assign the background color:
$('.gradeC td').on('click',function(e){
if(!$(this).closest('tr').hasClass('green')){
$(this).closest('tr').addClass('green');
}else{
$(this).closest('tr').removeClass('green');
}
});
See demo here

How to use dynamic id in jquery

I am using this to point a seperate td's in a table. And the id(dynid) are created dynamically so i need to change the position to absolute when user hover on a td. And i tries the below one but its not wroks
$('#selectTable tr td #td'+dynid).hover(
function () {
$(this).css("position","absolute");
}
);
Thanks in advance
You are looking for an element within the td element, but you want the td element with a certain id. There is whitespace. You need td#id instead of td #id.
dynid = 2; // Test
$('#selectTable tr td#td' + dynid).hover(
function () {
$(this).css("position","absolute");
}
);
A sample with background-color
http://jsfiddle.net/FKhbd/
You may want to define a second handler, if the hover ends. Something like this:
$('#selectTable tr td#td' + dynid).hover(
function () {
$(this).css("position","absolute");
},
function () {
$(this).css("position","relative");
}
);
Probably your selector is wrong: '#selectTable tr td #td'+dynid should become '#selectTable tr td#td'+dynid. You'd also be wise to toggle on and off a css class that sets position: absolute like so:
$("#selectTable td").hover(function () {
$(this).addClass("pos-abs"); // focus
}, function () {
$(this).removeClass("pos-abs"); // blur
});
See http://api.jquery.com/hover/

Categories

Resources