Add rows in HTML table with JavaScript - 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

Related

Table problems. Should I recreate and simplify the table with createElement and appendChild methods?

PROBLEM 1:
I cannot get imported array variables to stay as the array changes throughout use. The slice method creates a new array to my understanding and when I use a function on a button to slice the array and change the table itself, I send the sliced element above and remove it from the table. On function use, the button changes to a second function that does the same, but sends the second sliced out element up top and slices another element from the table.
QUESTION 1:
When I slice the array the second time it changes the first initial sliced element.
TABLE AND SCRIPT FORMAT:
I have a Top area where values that are removed from the table and selected are sent above as it's removed.
<div class='top-stick'>
<button style='width:50px; height: 50px'>X</button>
<p id='selectOne' style='text-align: center; background-color: lightgreen; border: solid 3px black; padding: 5px'>First Perk Selected</p>
<p id='selectTwo' style='text-align: center; background-color: lightgreen; border: solid 3px black; padding: 5px'>
Second Perk Selected</p>
<p id='selectThree' style='text-align: center; background-color: lightgreen; border: solid 3px black; padding: 5px'>
Third Perk Selected </p>
<p id='percenttotal' style='text-align: center; background-color: lightgreen; border: solid 3px black; padding: 5px'>Craft %</p>
</div>
<div>
above is the is the top section that receives the values chosen by the button.
<table id='myTable' style='background-color: lightgreen; padding: 5px'>
<tr>
<th style='width: 20px'> Click Box to Select Perk</th>
<th style='width: 100px'>Perk</th>
<th>Effect</th>
<th class='percent' style='width: 40px'>Craft %</th>
</tr>
<tr>
<td style='background-color: black; width: 75px'>
<button id='myBtn' value='1'>Select</button>
<td id='perkOne'></td>
<td id='perkOneEffect'></td>
<td id='perkOnePercent'></td>
</tr>
<tr>
<td style='background-color: black'>
<button id='myBtn'> Select </button>
<td id='perkTwo'></td>
<td id='perkTwoEffect'></td>
<td id='perkTwoPercent'></td>
</tr>
<tr>
<td style='background-color: black'>
<button id='myBtn'> Select </button>
<td id='perkThree'></td>
<td id='perkThreeEffect'></td>
<td id='perkThreePercent'></td>
</tr>
</table>
this is the table but it goes all the way up to 26 rows.
below is the function that imports all the variables into the empty table by Id before any buttons are pressed.
function importBefore() {
document.getElementById("perkOne").innerHTML = perkName[0];
document.getElementById('perkTwo').innerHTML = perkName[1];
document.getElementById('perkThree').innerHTML = perkName[2];
document.getElementById('perkFour').innerHTML = perkName[3];
document.getElementById('perkFive').innerHTML = perkName[4];
document.getElementById('perkSix').innerHTML = perkName[5];
document.getElementById('perkSeven').innerHTML = perkName[6];
document.getElementById('perkEight').innerHTML = perkName[7];
document.getElementById('perkNine').innerHTML = perkName[8];
document.getElementById('perkTen').innerHTML = perkName[9];
document.getElementById('perkEleven').innerHTML = perkName[10];
This is the button function that slices an array and modifies the display of the table while sending the removed array value to the above portion.
function first() {
var perkNameOne = perkName.slice(0, 26)
document.getElementById('selectOne').innerHTML = perkNameOne[0];
perkName = perkName.slice(1, 26);
perkEffect = perkEffect.slice(1, 26);
perkPercent = perkPercent.slice(1, 26);
document.getElementById('selectedFirst').innerHTML = null;
importFirst();
document.getElementById("myBtn").addEventListener("click", function() {
second();
});
}
I import the table itself then use a button to slice and import new values then change the button function at the end of each button press with a reset button at the top left.
The problem I am having is that
var perkNameOne = perkName.slice(0, 26)
document.getElementById('selectOne').innerHTML = perkNameOne[0];
this value changes with each button press that goes along even though
perkName = perkName.slice(1, 26);
I never slice perkNameOne again. To my understanding, slicing creates a new array...? I may need to remake the table and simplify it with an automatic createElement and appendChild method that creates rows based on length of array.
perkNameOne[0] changes to the newly sliced array further down the strip.
PROBLEM 2:
I also can't change perkName[0] to
let n = "";
for (let i = document.getElementById(myBtn).value; i = perkName; i) {
n = perkName[i];
or however that coding line goes. so I can write the button as-
<button id='myBtn' value='0'>Select</button>
<button id='myBtn' value='1'>Select</button>
function slice(a) {
return slice(a);
}
function first(document.getElementById('myBtn').this.value) {
var perkNameOne = perkName.slice(a, 26)
document.getElementById('selectOne').innerHTML = perkNameOne[0];
perkName = perkName.slice(a, 26);
perkEffect = perkEffect.slice(a, 26);
perkPercent = perkPercent.slice(a, 26);
document.getElementById('selectedFirst').innerHTML = null;
importFirst();
document.getElementById("myBtn").addEventListener("click", function() {
second();
});
}
and use the value of each line in itself instead of having 26 different functions on each button.
QUESTION FOR PROBLEM 2:
Not sure how I can get each button to slice the element out of the row it is in on the table so that I wouldn't have to make a different function and event listener for every single button.
I'm new to coding and this is my first complex interactive data-table.
Please fix the question, its very difficult to understand in the current format.
Here are a few tips:
use document.querySelector instead.
use plural words for values like arrays, and singular words for singular
perkNames instead of perkName
then perkName when you need to refer to a single perk's name
don't use spelled out numbers, it makes things more complex than needed.
you can swap the html ids with html classes, then select it inside js with document.querySelector('.perk:nth-child(1)') or something like this document.querySelector('.perks-container>:nth-child(1)')

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>

Jquery Append Table

html file
<div id='tweetPost'>
<table id="example">
<thead>
<tr>
<th>No</th>
<th>FistName</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
JavaScript
$("#tweetPost").append(<tr>);
$("#tweetPost").append("<td>"+tweets.statuses[i].text + "<td/>");
$("#tweetPost").append("<td>"+tweets.statuses[i].created_at +"</td>");
$("#tweetPost").append(</tr>);
Above code when i try to run it , the table wont come out.
Question : How can i append the td row inside tbody??
You should try targeting your table id example and the tbody like so:
$("#example tbody").append("<tr><td>text</td><td>created</td></tr>");
See this link for a working example: append to example table
$('#tweetPost').append('<table></table>');
var table = $('#tweetPost').children();
table.append("<tr><td>a</td><td>b</td></tr>");
table.append("<tr><td>c</td><td>d</td></tr>");
table {
background: #CCC;
border: 1px solid #000;
}
table td {
padding: 15px;
border: 1px solid #DDD;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='tweetPost'></div>
Note:- You can tackle your table id & the tbody
You are appending the tr in div instead of tbody and the is also some syntax error. Try like following.
$("#example tbody").append("<tr><td>" + tweets.statuses[i].text + "<td/><td>" + tweets.statuses[i].created_at + "</td><tr>");
You've missed inverted comma " " in first and last lines. Try this:
$("#tweetPost").append("<tr>");
$("#tweetPost").append("<td>"+tweets.statuses[i].text + "<td/>");
$("#tweetPost").append("<td>"+tweets.statuses[i].created_at +"</td>");
$("#tweetPost").append("</tr>");

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>

Setting the style property for table rows using 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');

Categories

Resources