Setting the style property for table rows using javascript - javascript

Assume I have a page like this
<html>
<body>
<table id="t1">
<tr><th>Head1</th><th>Head2</th></tr>
<tr><td>1</td><td>2</td></tr>
<tr><td>3</td><td>4</td></tr>
</table>
</body>
</html>
My CSS
table th { background:color1;}
table td { background:color2;}
How do I change the background color for all rows except header row with a javascript statement. Is looping through each row and column the only method?
I can get document.getElementById('t1').rows[1] and rows[2] and change background. But is there another efficient way?

You can loop over the elements and change the background
var els = document.getElementById("t1").getElementsByTagName("td");
for(var i=0;i<els.length;i++){
els[i].style.background = "green"
}

put a class on the rows and put backgrounds in css like you do with the tables

You can try this:
table th {background: color1;}
table tbody {background: color2;}
<table id="t1">
<tr><th>Head1</th><th>Head2</th></tr>
<tbody id="t2">
<tr><td>1</td><td>2</td></tr>
<tr><td>3</td><td>4</td></tr>
</tbody>
</table>
And in the script:
document.getElementById('t2').style.backgroundColor=color3;
EDIT
It's also possible to add a rule to the particular styleSheet.
CSS:
table th {background: color1;}
table td {background: color2;}
Script:
var sSheet = document.styleSheets[0];
if (sSheet.insertRule) {
sSheet.insertRule('td {background-color: color3}', sSheet.cssRules.length);
} else { // For IE < 9
sSheet.addRule('td', 'background-color: color3', -1);
}
You can also modify an existing rule itself:
var tdRule,
sSheet = document.styleSheets[0];
if (sSheet.cssRules) {
tdRule = sSheet.cssRules[1];
} else { // For IE < 9
tdRule = sSheet.rules[1];
}
tdRule.style.backgroundColor = color3;

I use JQuery.
$('td').css('background','#3232');

Related

Add rows in HTML table with JavaScript

I'd like to write <td> tags with JavaSctipt in my HTML code.
I'm building a <table> in the main code and I'd like to continue it with a <script>, adding rows in the division.
<body>
<table>
<tr>
<td>First</td>
</tr>
<div id="searchOutput"></div>
<tr>
<td>Last</td>
</tr>
</table>
<script>
document.getElementById("searchOutput").innerHTML = "<tr><td>Middle<td><tr>";
</script>
</body>
The problem is that the <script> creates another table in a strange way.
Is there a way to add rows without writing all code (including <table> tags) in the <script>?
For insert new row in the table, you can use Table insertRow() and insertCell() Methods. The insertRow() methods creates an empty <tr> element and adds it to a table. The insertCell() method inserts a cell into the current row.
See the code below:
function addRows() {
var table = document.getElementById( 'myTable' ),
row = table.insertRow(0),
cell1 = row.insertCell(0),
cell2 = row.insertCell(1);
cell1.innerHTML = 'Cell 1';
cell2.innerHTML = 'Cell 2';
}
table {
border: 1px solid #999;
border-collapse: collapse;
width: 100%
}
td {
border: 1px solid #999
}
<p>
<button onclick="addRows()">Add a new row</button>
</p>
<table id="myTable"></table>
CertainPerformance is correct; divs should not be direct children of tables. You might find this question useful. You have the right idea, if only you could actually replace the HTML of the div as opposed to simply filling it in. So, you could set the ID of the Last tr to searchOutput. Then, something like
var newRow = document.createElement("tr");
var oldRow = document.getElementById("searchOutput");
newRow.innerHTML = "<tr><td>Middle</td></tr>";
document.getElementByTagName("table").insertBefore(row, oldRow);
Take a look at the example from w3cschools.com https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_table_insertrow

How can I make my second selection working in JavaScript?

I am using the selection. I am selecting a value and getting the result in an input box, but the problem is, it is only working in the first row of my selection and not working when I am clicking second selection. Here is the code, Please share if you can solve this one or advice.
<script type="text/javascript">
function displayResult()
{
document.getElementById("mycall1").insertRow(-1).innerHTML = '<td><select id = "forcx" onchange="fillgap()"><option>Select</option> <option>Force</option><option>Angle</option><option>Area</option></select></td>';
document.getElementById("mycall2").insertRow(-1).innerHTML = '<td><input type="text" id="result1" size = "10" ></td>';
}
function fillgap(event){
var xnumb = 20;
var forcxlist = document.getElementById("forcx");
var forcxlistValue = forcxlist.options[forcxlist.selectedIndex].text;
if (forcxlistValue == "Force"){
document.getElementById("result1").value = xnumb;
}
}
</script>
Ok, so if i understand correctly
1) You want to add the: selection, results & + to the existing table
2) Add the options Force, Angle & Area to the select
3) If Force is selected, put the value '20' in the results td
4) When the + is clicked, a new row is added.
5 The newly added rows should behave exactly the same.
Given the above, I have done the following, I'm using jQuery as its simpler and I'm more familiar with it. Its easy.
The trick here is event delegation. at the time your page loads the new rows don't exist, that's why your JavaScript isn't working on them. you can read about it here: https://learn.jquery.com/events/event-delegation/
Here's the result:
$(document).ready(function() {
// add headers to table
$('table tr:first-child').append('<th>Result</th><th>Add</th>');
//add fields to table
$('table tr:not(:first-child)').append('<td><select class="selection"><option></option><option value="Force">Force</option><option value="Angle">Angle</option><option value="Area">Area</option></select></td><td class="result"></td><td><button type="button" class="displayResultBtn">+</button></td>');
// add new row when button is clicked
$('table').on('click','.displayResultBtn', function( event) {
var tRow = $(this).parent().parent().clone();
$(this).parents('table').append(tRow);
$('table tr:last-child td.result').empty();
});
// when the dropdown is changed, update the result to 20 if "Force" is selected.
$('table').on('change','.selection', function( event) {
var selection = $(this).val();
if (selection == "Force") {
$(this).parent().next().html('20');
// You can add more coditionals if you want to add didferent values for the other options.
} else {
$(this).parent().next().empty();
}
});
});
table,
td,
th {
border: 1px solid black;
white-space: nowrap;
}
table {
border-collapse: collapse;
width: 30%;
table-layout: auto;
}
td {
text-align: center;
vertical-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<table>
<tr>
<th>To</th>
<th>From</th>
<th>Detail</th>
<th>Selection</th>
</tr>
<tr>
<td>A</td>
<td>B</td>
<td>A+B</td>
</tr>
</table>
It's hard to answer with limited code provided, but I think your issue is that you are using id multiple times. Which is invalid. id should be unique and used once only.
I have put together some demo code here that will hopefully help you. It doesn't solve your exact problem(I dont have your html so i cant fully solve it). but hopefully this will give you an idea of how to handle accessing different rows, or specific unique ids.
I'm using jQuery here for simplicity, but the principle is the same:
Here's a fiddle if thats easier to play with: https://jsfiddle.net/BradChelly/4179e26q/
I hope this helps somewhat.
// highlight row by child selectors (:last-child)
$('#selectLastRowBtn').click(function(){
//clear any previous highlighting
$('#myTable tr:not(:first-child)').css('background-color','white');
// highlight the last row in the table.
$('#myTable tr:last-child').css('background-color','lightgrey');
});
// highlight row using a specific unique id
$('#selectRowByIdBtn').click(function(){
//get selected row id from dropdown
var rowId = $('#rowSelector option:selected').val();
//clear any previous highlighting
$('#myTable tr:not(:first-child)').css('background-color','white');
//highlight the row with the matching id from the selection dropdown
$('#myTable #row_'+rowId).css('background-color','lightgrey');
});
//
// ------Below is just stuff to make demo work, not relevant to the question
//
// Add row with unique id
$('#addNewRowBtn').click(function(){
var rowCount = $('#myTable tr').length;
$('#myTable').append('<tr id="row_'+rowCount+'"><td>23124</td><td>23124</td><td>23124</td><td>23124</td></tr>');
populateSelect(rowCount);
});
// populate select options
function populateSelect(rowCount){
$('#rowSelector').append('<option value="'+rowCount+'">'+rowCount+'</option>')
}
table {
width: 100%;
text-align: center;
}
table td {
border: 1px solid #333;
padding: 30px 0px;
}
table tr:first-child {
top: 0px;
background: #333;
}
table tr:first-child th {
color: #fff;
padding: 20px 0px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<table id="myTable">
<tr>
<th>Column One</th>
<th>Column Two</th>
<th>Column Three</th>
<th>Column Four</th>
</tr>
<tr id="row_1">
<td>23124</td>
<td>23124</td>
<td>23124</td>
<td>23124</td>
</tr>
</table>
<button id="addNewRowBtn">Add Row</button>
<h3>Using child selectors:</h3>
<button id="selectLastRowBtn">Highlight last row using child selector</button>
<h3>Highlight a row by id:</h3>
<select name="" id="rowSelector">
<option value="1">1</option>
</select>
<button id="selectRowByIdBtn">Highlight row by selected id</button>

Inserting ContentEditable into an HTML table

I am storing the html for a table in $scheduletext. I want to be able to edit any cell of the table when clicking it so I am using JQuery for the on click action. When I click on a cell it goes blank but will not allow me to type in it, what do I need to change to be able to type into this?
<html>
<body>
<div id="main">
<?php
print_r($scheduletext);
?>
</div>
<script type="text/javascript">
$('td').click(function(){
$(this).html("<contenteditable>");
});
</script>
</body>
</html>
For editing and testing purposes, since to run my code you also need the table, the CSS doesnt hurt either... I dumped it into JSfiddle to hopefully make it easier for anyone trying to give me a hand : https://jsfiddle.net/4yczepsj/
Thanks in advance!!
EDIT: For some reason JSfiddle doesnt do anything at all when clicked on, but on the live model on my site the cell goes blank when clicked, but nothing can be entered.
In calling .html("<contenteditable>") you're modifying the inner HTML of your td element to contain a <contenteditable> element (which isn't valid). What you actually want to do is set the contenteditable property:
$(this).prop('contenteditable', true);
contentEditable is an attribute.
Try this :
$(this).attr('contentEditable', true);
Content Editable is an attribute, not an element. You want to add the attribute contenteditable to the the elements you want to have editable content.
$('td').click(function(){
$(this).attr("contenteditable");
});
https://jsfiddle.net/4yczepsj/1/
$('table').on('mousedown', 'td', function (event) {
$(event.target).closest('td').prop("contentEditable", true);
});
NOTE this includes information that the other answers contain, credit to them, but I am adding a little bit more and putting it all on one place.
I made the following changes:
added tabindex so table cells are tabable.
give focus to the table cell on click.
add contenteditable attribute on focus.
select contents of table cell on focus.
remove contenteditable on blur(when the td loses focus).
function setSelection(element) {
// code for selection from http://stackoverflow.com/questions/3805852/select-all-text-in-contenteditable-div-when-it-focus-click#answer-3806004
setTimeout(function() {
var sel, range;
if (window.getSelection && document.createRange) {
range = document.createRange();
range.selectNodeContents(element);
sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
} else if (document.body.createTextRange) {
range = document.body.createTextRange();
range.moveToElementText(element);
range.select();
}
}, 0)
}
// add tabindex to all tds.
$('td').attr('tabindex', 0);
$('td').on('focus', function() {
$(this).attr('contenteditable', true);
setSelection(this);
}).on('blur', function() {
$(this).attr('contenteditable', false);
})
table,
th,
td {
border: 1px solid black;
border-collapse: collapse;
font-size: 90%;
}
th,
td {
padding: 8px;
}
td {
text-align: center;
}
table {
margin: 0 auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<div id="main">
<table>
<tr>
<th></th>
<th>22oz Dark</th>
<th>12ct 4oz Dark</th>
</tr>
<tr>
<th>2016-01-01</th>
<td>9785</td>
<td>2478</td>
</tr>
<tr>
<th>2016-01-02</th>
<td>8754</td>
<td>2136</td>
</tr>
<tr>
<th>2016-01-03</th>
<td>13587</td>
<td>2203</td>
</tr>
<tr>
<th>2016-01-04</th>
<td>14111</td>
<td>3297</td>
</tr>
<tr>
<th>2016-01-05</th>
<td>13212</td>
<td>3101</td>
</tr>
<tr>
<th>2016-01-06</th>
<td>16335</td>
<td>3299</td>
</tr>
<tr>
<th>2016-01-07</th>
<td>15421</td>
<td>3100</td>
</tr>
</table>
</div>
</body>
</html>

jQuery .click() function how to distinguish table rows

Im trying to use the .click function on the UP and DN so that when I press up, the .over class is moved over onto the upper row and when I press DN the .over class is moved over onto the lower row. My problem is that I dont know how to specify a for loop into the click function and be able to call each row. All I know is how to specify which action the click functions with div ids.
<html>
<style>
.highlight{
background-color: pink;
}
}
.odd{
background-color: lightgrey;
}
.even{
background-color: gray;
}
.over{
background-color: red;
</style>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$('.c').addClass('highlight');
$('.a').addClass('odd');
$('.b').addClass('even');
});
</script>
</head>
<body>
<h2>2: Zebra Striping Demo</h2>
<table id = "myTable" width="200" border="1">
<caption><a id = "up" href="#">UP</a> Zebra Striping Demo <a id = "down" href="#">DN</a></caption>
<tr class = "a"><td>January</td> <td>February</td><td>March</td></tr>
<tr class = "b"><td>April</td><td>May</td><td>June</td></tr>
<tr class = "c"><td>July</td><td>August</td><td>September</td></tr>
<tr class = "a"><td>October</td><td>November</td><td>December</td></tr>
<tr class = "b"><td>Monday</td><td>Tuesday</td><td>Wednesday</td></tr>
<tr class = "a"><td>Thursday</td><td>Friday</td><td>Saturday</td></tr>
<tr class = "b"><td>Spring</td><td>Summer</td><td>Fall</td></tr>
</table>
</body>
</html>
Here is the solution you are looking for.
http://jsfiddle.net/90xxguma/
<html>
<head>
<style>
.highlight{
background-color: pink;
}
.odd{
background-color: lightgrey;
}
.even{
background-color: gray;
}
.over{
background-color: red;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$('.c').addClass('highlight');
$('.a').addClass('odd');
$('.b').addClass('even');
var currentRow = -1;
var totalRows = $('#myTable tr').length;
$('#down').click(function(){
if(currentRow != (totalRows-1))
{
currentRow++;
$('#myTable tr').removeClass('over');
$('#myTable tr:eq('+currentRow+')').addClass('over');
}
})
$('#up').click(function(){
if(currentRow > 0)
{
currentRow--;
$('#myTable tr').removeClass('over');
$('#myTable tr:eq('+currentRow+')').addClass('over');
}
})
});
</script>
</head>
<body>
<h2>2: Zebra Striping Demo</h2>
<table id = "myTable" width="200" border="1">
<caption><a id = "up" href="#">UP</a> Zebra Striping Demo <a id = "down" href="#">DN</a></caption>
<tr class = "a"><td>January</td> <td>February</td><td>March</td></tr>
<tr class = "b"><td>April</td><td>May</td><td>June</td></tr>
<tr class = "c"><td>July</td><td>August</td><td>September</td></tr>
<tr class = "a"><td>October</td><td>November</td><td>December</td></tr>
<tr class = "b"><td>Monday</td><td>Tuesday</td><td>Wednesday</td></tr>
<tr class = "a"><td>Thursday</td><td>Friday</td><td>Saturday</td></tr>
<tr class = "b"><td>Spring</td><td>Summer</td><td>Fall</td></tr>
</table>
</body>
</html>
JavaScript is not the appropriate solution for this: use CSS.
Alternating table rows:
tr:nth-child(even) {background: #CCC}
tr:nth-child(odd) {background: #FFF}
For the mouse click, use the css :active (and possibly :visited) pseudo selectors.
try this:
$("#up").on("click",function() {
$(".highlight").next().addClass("highlight").prev().removeClass("highlight");
})
$("#down").on("click",function() {
$(".highlight").prev().addClass("highlight").next().removeClass("highlight");
})
try that
You can use data-* attrbiutes.You can assign the order of the rows to the data-order attribute and when you click up for example; you can check the order and you can assign the class to the row with the order-1 tr.
jsfiddle link
jsfiddle
let me know if it works for you
what about this:
//use important for css .highlight class
$('#myTable tr').on('click',function(){
$('#myTable tr').removeClass("highlight");
$(this).addClass("highlight");
});
//for mouse over and out
$('#myTable tr').mouseover(function(){
$(this).addClass('over');
}).mouseout(function(){
$(this).removeClass('over');
});
link example

Container element inside of a table that holds rows

I am dynamically inserting a table row (or multiple rows) into a table upon an ajax call's return. I am looking to accomplish this by having an empty container type element inside of my html table that I can insert <tr> elements into. As I have seen from other posts, a div cannot hold a tr element, so my question is, is there a particular way that I can insert the html for row(s) into a table? It must be dynamic in nature, or in other words I need to be able to hold more than just one <tr>.
You can append to last row of table.
<table>
<tr><td>First Row</td></tr>
<tr><td>Middle Row</td></tr>
<tr><td>Last Row</td></tr>
</table>
<script>
$( "#tableid tr:last" ).append(
</script>
Assuming you aren't using jQuery, you can do something like this:
var myTable = document.getElementById('myTable').getElementsByTagName('tbody')[0];
var row = myTable.insertRow(myTable.rows.length);
You can then insert cells using insertCell on row.
Alternatively, if you have jQuery,
$("#myTable").append("<tr><td>Table Row with cell!</td></tr>");
I'm not sure why you wouldn't just use the <table> element directly, but you can use <tbody> elements as row containers within a table.
onload = function(){
document.getElementById("aButton").onclick = addRow.bind(null, "a");
document.getElementById("bButton").onclick = addRow.bind(null, "b");
}
function addRow(id) {
var r = document.getElementById(id).insertRow(-1);
var c = r.insertCell(-1);
c.innerHTML = "Row added at " + new Date().toLocaleTimeString();
}
body {
font-family: sans-serif;
font-size: 12px;
}
table {
border-collapse: collapse;
margin: 8px 0;
}
td {
border: 1px solid #ccc;
padding: 1px 2px;
}
<button id="aButton">Add row to 'A'</button>
<button id="bButton">Add row to 'B'</button>
<table>
<tbody><tr><td>Before A</td></tr></tbody>
<tbody id="a"></tbody>
<tbody>
<tr><td>After A</td></tr>
<tr><td>Before B</td></tr>
</tbody>
<tbody id="b"></tbody>
<tbody><tr><td>After B</td></tr></tbody>
</table>

Categories

Resources