Adding new row to table with three columns Javascript html click function - javascript

Desrciption
I'd like to able to add a row using javascript with three columns to a table in html.
I am creating a table where the user can enter their own text and add the text along with two other pieces of information to the table into three columns. The current code that I have will not display the new row. The code also includes a drag and drop feature where the user can click on the row and drag it into a different position into the table.
I am asking for guidance as to why when I press the click button it does not add a new row to the table.
edit: Code is now working after update, but the else statement does not do anything.
Javascript
function addRow(mytable) {
var food = document.createTextNode(document.querySelector('.input').value);
var category = document.createTextNode(document.querySelector('.input2').value);
var time = document.createTextNode(document.querySelector('.input3').value);
document.querySelector('.input').value = '';
document.querySelector('.input2').value = '';
document.querySelector('.input3').value = '';
// Get a reference to the table
if (food !== '') {
var tableRef = document.getElementById(mytable);
var attr = document.createAttribute('draggable');
attr.value = 'true';
// Insert a row at the end of the table
var newRow = tableRef.insertRow(-1);
newRow.setAttributeNode(attr);
newRow.className = 'draggable';
// Insert a cell in the row at index 0
var newCell = newRow.insertCell(0);
var newCell2 = newRow.insertCell(1);
var newCell3 = newRow.insertCell(2);
var newText = food;
var newText2 = category;
var newText3 = time;
newCell.appendChild(newText);
newCell2.appendChild(newText2);
newCell3.appendChild(newText3);
addEventsDragAndDrop(newRow);
}
//not working for some reason
else {
document.getElementById("msg").innerHTML = "Please enter a name";
}
}
javascript click
document.getElementById('btn').addEventListener('click', function( {addRow('mytable');});
HTML
<table id="mytable">
<tr>
<th>Component</th>
<th>Category</th>
<th>Time</th>
</tr>
<div id="addRow"></div>
</table>

Few adjustments below, but more detail needed, atm only one text input for component, but can add more for cook/time
function addRow(mytable) {
var newItem = document.createTextNode(document.querySelector('.input').value);
var category = document.createTextNode("Cook");
var time = document.createTextNode("time");
document.querySelector('.input').value = '';
// Get a reference to the table
if (newItem != '') {
var tableRef = document.getElementById(mytable);
var attr = document.createAttribute('draggable');
attr.value = 'true';
// Insert a row at the end of the table
var newRow = tableRef.insertRow(-1);
newRow.setAttributeNode(attr);
newRow.className = 'draggable';
// Insert a cell in the row at index 0
var newCell = newRow.insertCell(0);
var newCell2 = newRow.insertCell(1);
var newCell3 = newRow.insertCell(2);
var newText = newItem;
var newText2 = category;
var newText3 = time;
newCell.appendChild(newText);
newCell2.appendChild(newText2);
newCell3.appendChild(newText3);
addEventsDragAndDrop(newRow);
}
}
document.getElementById('btn').addEventListener('click', function(){addRow('mytable');});
<table id="mytable">
<tr>
<th>Component</th>
<th>Category</th>
<th>Time</th>
</tr>
<tr class="draggable" id="draggable" draggable="true">
<td>Food goes here</td>
<td>Cook</td>
<td>10</td>
</tr>
<div id="addRow"></div>
</table>
<label for='component'>component</label>
<input class='input' id='component' />
<button id='btn'>add component</button>

Related

Adding a row on top-1 position in html table

function addRowtoTop(first) {
// get input values
var fname = document.getElementById('fname').value;
var lname = document.getElementById('lname').value;
var city = document.getElementById('city').value;
var country = document.getElementById('country').value;
// get the html table
// 0 = the first table
var table = document.getElementsByTagName('table')[0];
// add new empty row to the table
// 0 = in the top
// table.rows.length = the end
// table.rows.length/2+1 = the center
var newRow = table.insertRow((table.rows.length / 0));'
i have been trying to add a row on top-1 position on a html table but cant figure out how. by this line var newRow = table.insertRow((table.rows.length / 0)); i am able to add the row on top but it gets added above the heading part. Thanks in advance
you need to store the head in a variable, then the new row and then take the rest of the rows,
at the end, just table.innerHTML = newTable;
function addRow(){
var table = document.querySelector('table');
var Head = table.children[0].children[0].outerHTML;
var newRow = '<tr><td>newShoes</td><td>Shoes</td><td>Shoes</td></tr>';
var restOfTheTable = '';
for(var i = 1; i<=table.children[0].children.length-1; i++){
restOfTheTable += (table.children[0].children[i].outerHTML);
}
table.innerHTML = `${Head}${newRow}${restOfTheTable}`;
}
<table>
<tr>
<td>name</td>
<td>Price</td>
<td>Location</td>
</tr>
<tr>
<td>Shoes</td>
<td>Shoes</td>
<td>Shoes</td>
</tr>
<tr>
<td>Shoes</td>
<td>Shoes</td>
<td>Shoes</td>
</tr>
</table>
<button onclick="addRow()">add row</button>

How to let the user set the table size in HTML?

i want the user to enter the number of rows in a HTML table, how do i do that? this is where is stopped.
var x = prompt("how many rows?");
for ( var count=1)
document.writeln(<tr>)
count++;
{
if (count==x)
break;
}
You code is incomplete and moreover a mess. You wrote for statement without curly braces and the curly braces you put, it way after where it supposed to be.
If you wish to create a row inside a document, at least you need to create a html table first. (You can also do this using JavaScript)
<table>
<tbody>
</tbody>
</table>
Then you can move onto the JS part where user will be asked for input.
Here is a full example.
var x = prompt("how many rows?");
let count = 1;
let table = document.querySelector("table");
for (count = 1; count <= x; count++) {
// insert a row
var row = table.insertRow(0);
// create two cell
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
// default text if you want
cell1.innerHTML = "Cell 1"
cell2.innerHTML = "Cell 2";
}
<table>
<tbody>
</tbody>
</table>
You could do something simple like this:
const inputEl = document.querySelector('#input-el');
const buttonEl = document.querySelector('#button-el');
const divEl = document.querySelector('#table-display');
buttonEl.addEventListener('click', e => {
const rowQty = inputEl.value;
let html = `<table id="tableEl-${rowQty}" border="1">`;
for (let i = 0; i < rowQty; i++) {
html += `<tr><td>${i+1}</td><td>Row ${i + 1}</td></tr>`;
}
html += `</table>`;
divEl.innerHTML = html;
});
<label id="label-el" for="input-el">Number of rows</label>
<input id="input-el" type="text" />
<input id="button-el" type="button" value="Create table" />
<div id="table-display"></div>

Delete table rows having selected id using javascript

I am trying to make the code to add and remove desired rows on selecting id in the select box. My code is below :
HTML code :
<body>
<table id="table" border="1" style="float:left">
<tr>
<td>Employee id</td>
<td>Name</td>
<td>Designation</td>
</tr>
</table>
<select id="select_id" style="float:right">
<option>--select--</option>
<option value="1">1</option>
<option value="2">2</option>
</select><br/><br/>
<button onclick="delete_row()" style="float:right">remove</button>
<button onclick="include()" style="float:right">add</button>
</body>
My javascript code :
<script type="text/javascript">
var employees=new Array(2);
for(i=0;i<2;i++)
employees[i] = new Array(3);
employees[0][0] = 1;
employees[0][1] = "Rahul";
employees[0][2] = "Administer";
employees[1][0] = 2;
employees[1][1] = "Raj";
employees[1][2] = "Manager";
function include(){
var id = document.getElementById("select_id").value;
var table = document.getElementById("table");
var row = table.insertRow();
id=id-1;
var col1 = row.insertCell(0);
var col2 = row.insertCell(1);
var col3 = row.insertCell(2);
col1.innerHTML = employees[id][0];
col2.innerHTML = employees[id][1];
col3.innerHTML = employees[id][2];
}
</script>
Add button works fine. but for remove button I cant get a function to remove all the rows with selected id. Can anyone suggest me?
My code in jsfiddle : https://jsfiddle.net/noona/fNPvf/23235/
use querySelectorAll and rowIndex to achieve this. here is your updated code
var employees = new Array(2);
for (i = 0; i < 2; i++)
employees[i] = new Array(3);
employees[0][0] = 1;
employees[0][1] = "Rahul";
employees[0][2] = "Administer";
employees[1][0] = 2;
employees[1][1] = "Raj";
employees[1][2] = "Manager";
function include() {
var id = document.getElementById("select_id").value;
var table = document.getElementById("table");
var row = table.insertRow();
id = id - 1;
row.id = id;
var col1 = row.insertCell(0);
var col2 = row.insertCell(1);
var col3 = row.insertCell(2);
col1.innerHTML = employees[id][0];
col2.innerHTML = employees[id][1];
col3.innerHTML = employees[id][2];
}
function delete_row() {
var id = document.getElementById("select_id").value - 1;
var table = document.getElementById("table");
rowsCount = table.querySelectorAll('tr[id="' + id + '"');
for (var i = 0; i < rowsCount.length; i++) {
table.deleteRow(rowsCount[i].rowIndex);
}
}
<table id="table" border="1" style="float:left">
<tr>
<td>Employee id</td>
<td>Name</td>
<td>Designation</td>
</tr>
</table>
<select id="select_id" style="float:right">
<option>--select--</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<br/>
<br/>
<button onclick="delete_row()" style="float:right">remove</button>
<button onclick="include()" style="float:right">add</button>
When adding a new row, give the newly added rows an attribute that holds it's id value. Then you can delete all the rows whose attribute value is equal to selected id in dropmenu.
you can try below:
function include(){
var table = document.getElementById("table");
var id = document.getElementById("select_id").value;
var table = document.getElementById("table");
var row = table.insertRow();
// give the new row an attribute that can identify itself
row.setAttribute("emplId",id);
id=id-1;
var col1 = row.insertCell(0);
var col2 = row.insertCell(1);
var col3 = row.insertCell(2);
col1.innerHTML = employees[id][0];
col2.innerHTML = employees[id][1];
col3.innerHTML = employees[id][2];
}
function delete_row() {
var table = document.getElementById("table");
var id = document.getElementById("select_id").value;
for(var i = 0; i<table.rows.length; i++) { // iterate through the rows
var rowEmplId = table.rows[i].getAttribute("emplId");
if(rowEmplId==id) { // found a row matches the selected option
table.deleteRow(i); // remove this row
i--; // we just removed a row, so we need to adjust the cursor
}
}
}

How to insert new rows in some position in table

I have page with table.
In tbody I show data via angularjs. In thead I have same row as in tbody, but its empty, and when I filled input field and click somewhere (focus lost), one row adds to my table (thead). And I need to make some flag on filled row, as like - rowAdded = true, because without that I clicking on input of one row and rows adds. And one more problem is that rows adds to the end of table.
it's all works on this script:
var tbody = $('.table-timesheet thead');
tbody.on('blur', ':text', function () {
var tr = $(this).closest('tr'),
notEmpty = $(':text', tr).filter(function () {
return $.trim($(this).val()) != '';
}).length;
if (notEmpty) {
$('.note-input').css('width', '88%').css('float', 'left');
$('.timesheet-delete-button').css('display', 'block');
//tr.clone(true).appendTo(tbody).find(':text').val('');
insRow();
}
});
function deleteRow(row) {
var i = row.parentNode.parentNode.rowIndex;
document.getElementById('table-body').deleteRow(i);
}
function insRow() {
var table = document.getElementById('table-body');
var newRow = table.rows[1].cloneNode(true);
var len = table.rows.length;
newRow.cells[0].innerHTML = len;
var inp1 = newRow.cells[1].getElementsByTagName('input')[0];
inp1.id += len;
inp1.value = '';
var inp2 = newRow.cells[2].getElementsByTagName('input')[0];
inp2.id += len;
inp2.value = '';
table.appendChild(newRow);
}
There is my example in plunker:
http://plnkr.co/edit/rcnwv0Ru8Hmy7Jrf9b1C?p=preview
Is this what you are looking for
function insRow(ind){
var table = document.getElementById('table-body');
var newRow = table.rows[1].cloneNode(true);
var len = table.rows.length;
newRow.cells[0].innerHTML = ind!==undefined ? ind : len;
if(ind!==undefined)
$(table).find('tr:eq('+ind+')').before(newRow);
else table.appendChild(newRow);
}
insRow(2);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="table-body">
<tbody>
<tr><td>1</td></tr>
<tr><td>2</td></tr>
<tr><td>3</td></tr>
</tbody>
</table>

local storage table

i am storing my values into a local storage, and i am trying to display the information in a table, but it doesnt seem to work and it always outputs it into the first column go down vertically.
for example i want it to come out like this when i enter my information
|Balance|Name|Quantity|Price|
| 100 |test| 100 | 1.99|
but instead it is currently displaying like this:
|Balance|Name|Quantity|Price|
|100|
|test|
|100|
|1.99|
This is the code for my local storage
function save(item) {
var playlistArray = getStoreArray("playlist");
playlistArray.push(item);
localStorage.setItem("playlist", JSON.stringify(playlistArray));
}
function Load_storage() {
var playlistArray = get_Storage();
var ul = document.getElementById("playlist");
if (playlistArray != null) {
for (var i = 0; i < playlistArray.length; i++)
{
var li = document.createElement("table");
li.innerHTML = playlistArray[i];
ul.appendChild(li);
}
}
}
function get_Storage() {
return getStoreArray("playlist");
}
function getStoreArray(key) {
var playlistArray = localStorage.getItem(key);
if (! playlistArray) {
playlistArray = new Array();
}
else {
playlistArray = JSON.parse(playlistArray);
}
return playlistArray;
}
And i put into my local storage via this function
var table=document.getElementById("myTable");
var row=table.insertRow(1);
var cell1=row.insertCell(0); // bank account
var cell2=row.insertCell(1); // name
var cell3=row.insertCell(2); // Quantity
var cell4=row.insertCell(3); // price
cell1.innerHTML=Balance ; // bank account
cell2.innerHTML=name; //stock symbol
cell3.innerHTML=quantity; // Quantity
cell4.innerHTML=price; // bought
var SAVE= document.getElementById("myTable");
SAVE.appendChild(row);
save(cell1.innerHTML);
save(cell2.innerHTML);
save(cell3.innerHTML);
save(cell4.innerHTML);
// save(Balance+"......................."+
name+"......................."+
quantity+"......................."+
price + ".......................");
this is commented out because it will always show the line but i dont want it that way even tho this way does work
Put the table column headers in your html. It is much more efficient than doing it with JavaScript:
<body>
<table id='myTable'>
<thead>
<tr>
<th>Balance</th>
<th>Name</th>
<th>Quantity</th>
<th>Price</th>
</tr>
</thead>
</table>
</body>
Some changes to your JavaScript:
var table = document.getElementById("myTable"),
row = table.insertRow(1),
cell1 = row.insertCell(0), // bank account
cell2 = row.insertCell(1), // name
cell3 = row.insertCell(2), // Quantity
cell4 = row.insertCell(3), // price
testBalance = '3.00',
testName = 'Mike',
testQuantity = '2.00',
testPrice = '5.00';
cell1.innerHTML = testBalance; // bank account
cell2.innerHTML = testName; //stock symbol
cell3.innerHTML = testQuantity; // Quantity
cell4.innerHTML = testPrice; // bought
//you can remove these lines
//var SAVE = document.getElementById("myTable");
//SAVE.appendChild(row);
save(cell1.innerHTML);
save(cell2.innerHTML);
save(cell3.innerHTML);
save(cell4.innerHTML);
// save(Balance+"......................."+
// name + "......................." +
// quantity + "......................." +
//price + //".......................");
Here is a jsFiddle.
I hope this helps :-)

Categories

Resources