Adding multiple rows in html table dynamically using Javascript - javascript

Adding a single row in a table (html) and deleting it, using JavaScript, is simple. But, is it possible to add multiple rows, like 2 or more, by calling the addrow function only once? The added rows will have different elements, like first row will be having a textfield, the other a textarea and like that...
Is there any other alternative in html to do that?

I solved it by myself by writing code similar to this :
adding three rows,first with a textfield,second having a textarea and the third having a button
function addRow(tableId)
{
var addrow=1;
var table=document.getElementById(tableId);
var rowCount=table.rows.length;
for(var i=1;i<=3;i++)
{
if(addrow==1)
{
var newRow=table.insertRow(rowCount);
var cell0=newRow1.insertCell(0);
var element0=document.createElement("input");
element0.type="text";
cell0.appendChild(element0);
}
if(addrow==2)
{
var newRow2=table.insertRow(rowCount);
var cell0=newRow1.insertCell(0);
var element0=document.createElement("textarea");
cell0.appendChild(element0);
}
if(addrow==3)
{
var newRow3=table.insertRow(rowCount);
var cell0=newRow1.insertCell(0);
var element0=document.createElement("input");
element0.type="button";
cell0.appendChild(element0);
}
addrow++;
}
}
Each time the for loop runs, a new html element is added in the table and hence I got three rows added dynamically each having a different element .

You can define your methods as follows:
addRow(var rowCount)
{
for(var i=0; i<rowCount; i++)
{
// Your current implementation to add a row
}
}
Similarly, deleteRow(var rowCount) can be defined.

function gen_textbox(tr, id, name, type, value){
td = document.createElement("td");
tr.appendChild(td);
var input = document.createElement("input");
input.setAttribute("id", id);
input.setAttribute("name", name);
if(type == "text"){
input.setAttribute("type", "text");
}
else if (type == "hidden") {
input.setAttribute("type", "hidden");
}
else{
input.setAttribute("type", "pass");
}
input.setAttribute("value", value);
td.appendChild(input);
}
function gen_hiddenbox(node, id, name, value){
var input = document.createElement("input");
input.setAttribute("id", id);
input.setAttribute("name", name);
input.setAttribute("type", "hidden");
input.setAttribute("value", value);
node.appendChild(input);
}
function gen_label(tr, id, text){
td = document.createElement("td");
tr.appendChild(td);
var input = document.createElement("label");
input.setAttribute("id", id);
var rtext = document.createTextNode(text);
input.appendChild(rtext);
td.appendChild(input);
}
function gen_label(tr, id, text, td_class){
td = document.createElement("td");
td.setAttribute("class", td_class);
tr.appendChild(td);
var input = document.createElement("label");
input.setAttribute("id", id);
var rtext = document.createTextNode(text);
input.appendChild(rtext);
td.appendChild(input);
}
function getKeyValueFromJSON(jsonObj, valueNames) {
var value, text = "", temp="";
obj= '{ "ValueText": [';
for(var i=0; i<jsonObj.length; i++) {
text = "";
for(var j=0; j<valueNames.length; j++) {
temp="jsonObj[i]."+valueNames[j];
text = text+eval(temp)+" <b>|</b> ";
}
value = jsonObj[i].id;
if(i<jsonObj.length-1)
obj = obj+'{ "value": "'+value+'", "text": "'+text+'" },';
else
obj = obj+'{ "value": "'+value+'", "text": "'+text+'" }';
}
obj=obj+"]}";
return obj;
}
function gen_select(tr, DrdId, Drdname, multiple, Drdsize, Drdnode, jsonObj) {
td = document.createElement("td");
tr.appendChild(td);
var select = document.createElement("select");
select.setAttribute("id", DrdId);
select.setAttribute("name", Drdname);
if(multiple == true){
select.setAttribute("multiple", "multiple");
}
select.setAttribute("size", Drdsize);
var option;
option = document.createElement("option");
option.setAttribute("value", "Select "+Drdnode);
option.innerHTML = "Select "+Drdnode;
select.appendChild(option);
for(var i=0; i<jsonObj.length; i++){
option = document.createElement("option");
option.setAttribute("value", jsonObj[i].value);
option.innerHTML = jsonObj[i].value+" : "+jsonObj[i].text;
select.appendChild(option);
}
td.appendChild(select);
}
function gen_button(tr, id, value, onclk_fun) {
td = document.createElement("td");
tr.appendChild(td);
var button = document.createElement("input");
button.setAttribute("type", "button");
button.setAttribute("id", id);
button.setAttribute("value", value);
button.setAttribute("onclick", onclk_fun);
td.appendChild(button);
}
function gen_button(tr, id, value, onclk_fun, Class) {
td = document.createElement("td");
tr.appendChild(td);
var button = document.createElement("input");
button.setAttribute("type", "button");
button.setAttribute("id", id);
button.setAttribute("value", value);
button.setAttribute("onclick", onclk_fun);
button.setAttribute("class", Class);
td.appendChild(button);
}
function clearSelected(sel_id) {
var elements = document.getElementById(sel_id).options;
for(var i = 0; i < elements.length; i++){
elements[i].selected = false;
}
}
First create Generic Function to Add dynamically button, textbox and etc
function create_hiddenBox() {
/*
This is only for Spring form
In jsp and spring suppose <form:select path="evp_veh_id.veh_id" size="1" >
var sel_veh = document.getElementById("evp_veh_id.veh_id");
var veh_name = sel_veh.options[sel_veh.selectedIndex].text;
*/
var node = document.getElementById("evp_footer");
gen_hiddenbox(node, "evp_veh_name", "evp_veh_name", veh_name);
}
This is called for call generic dynamically way to make html component using JavaScript

Related

Delete a row from a table (HTML/JS)

Title is pretty self-explanatory; I'm trying to add a delete button to each row of a table, but right now it's deleting the table headers instead of the actual row. This is the Javascript; any tips?:
function addRow() {
var table = document.getElementById("todayTasks");
var row = document.createElement('tr');
row.id = "new_add";
var td0 = document.createElement("INPUT");
td0.type = "checkbox";
td0.id = "checkbox";
td0.onchange = updateItem;
var td1 = document.createElement('td');
var td2 = document.createElement('td');
var td3 = document.createElement("input");
td3.type = "button";
td3.value = "Delete";
td3.onclick = deleteFn;
if (document.getElementById('task').value === "") {
alert("Please provide a task.");
} else if (document.getElementById('duration').value === "") {
alert("Please provide a duration.");
} else {
td1.innerHTML = document.getElementById('task').value;
td2.innerHTML = document.getElementById('duration').value;
row.appendChild(td0);
row.appendChild(td1);
row.appendChild(td2);
row.appendChild(td3);
table.children[0].insertBefore(row, table.children[0].childNodes[1]);
}
function updateItem() //Cross out when checked
{
if (document.getElementById("checkbox").checked) {
document.getElementById("new_add").style.textDecoration = "line-through"
} else {
document.getElementById("new_add").style.textDecoration = "none"
}
}
function deleteFn(x) {
var i = x.rowIndex;
document.getElementById("todayTasks").deleteRow(i);
}
Your delete function take an event as an argument, that event hold a reference to the element via its property target. you can than get the tr which is the parent element of your input (if you wrap the input inside a td it would be the grand parent), then you can juste remove this element from the table
function deleteFn(event) {
var input = event.target;
var currentRow = input.parentNode;
document.getElementById("todayTasks").removeChild(currentRow);
}

adding row to an existing table in javascript

guys i jnow it is dummy question but i spent hours in this and cant reach .. i want to add row to an existing table and this row consists of checkbox and 4 textboxes .. when i run it the textboxes appears but the checkbox dont .. here is my code
function addRow() {
var i = 1;
var table = document.getElementById("table");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var html = [];
html.push("<table id='table'>\n<body>");
html.push("<tr><td><input type='checkbox' name='chk'/></td>");
var cell = row.insertCell(html);
for ( var propertyNames in grid.data[0]) {
cell = row.insertCell(i);
var element = document.createElement("input");
element.type = "text";
element.size = 10;
element.name = "input"+i;
cell.appendChild(element);
html.push("<td>" + cell + "</td>");
i++;
}
html.push("</tr>");
html.push("</body>\n</table>");
}
The problem is you are creating a array with the markup for the checkbox, but it is never added to the table
function addRow() {
var i = 1;
var table = document.getElementById("table");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell = row.insertCell();
var element = document.createElement("input");
element.type = "checkbox";
element.name = "chk";
cell.appendChild(element);
for (var propertyNames in grid.data[0]) {
cell = row.insertCell(i);
element = document.createElement("input");
element.type = "text";
element.size = 10;
element.name = "input" + i;
cell.appendChild(element);
i++;
}
}
var grid = {
data: [{
x: 1,
y: 1
}]
};
addRow();
<table id="table"></table>

hide with js an HTML table row <tr> so that it takes up no space

I am creating rows in a table with javascript. When I try to hide those rows, it hides the row, but the space of the row is still taken.
My code:
for (var i = 0; i < 8; i++) {
isHide = false;
if(i<3)
isHide = true;
var table = document.getElementById("table");
var tr = document.createElement("TR");
if (isHide == true) {
tr.style.visibility = "none";
}
else {
tr.style.visibility = "visible";
}
table.appendChild(tr);
var td1 = document.createElement("TD");
var td2 = document.createElement("TD");
tr.appendChild(td1);
tr.appendChild(td2);
var checkbox = document.createElement('input');
checkbox.type = "checkbox";
checkbox.name = i;
checkbox.value = i;
checkbox.id = i;
var label = document.createElement('label')
label.htmlFor = i;
label.appendChild(document.createTextNode(i.toString()));
if (isHide == false){
var mybr = document.createElement('br');
}
td1.appendChild(label);
td2.appendChild(checkbox);
}
How do I hide rows in a way that they do not take up any space?
Change tr.style.visibility = "none"; to tr.style.display = 'none'
With display:none, there will be no space allocated for the tr as tr will not appear on the page and we can interact with the tr through the DOM.
With visibility:hidden the tr is not visible but it takes up the space allocated to it. This means that tr is rendered on the page but does not seem to be visible.

Delete the row you click on (Javascript dynamic table)

I want to delete a row from a table, I am using Javascript.
I am dynamically creating table rows and in the last cell I have delete button so how to make it delete the row?
var newData4 = document.createElement('td');
var delButton = document.createElement('input');
delButton.setAttribute('type', 'button');
delButton.setAttribute('name', 'deleteButton');
delButton.setAttribute('value', 'Delete');
newData4.appendChild(delButton);
newRow.appendChild(newData4);
this is the function for creating my table rows
function addItem()
{
document.getElementById('add').onclick=function()
{
var myTable = document.getElementById('tbody');
var newRow = document.createElement('tr');
//var element1 = document.createElement("input");
//element1.type = "checkbox";
//newRow.appendChild(element1);
var newData1 = document.createElement('td');
newData1.innerHTML = document.getElementById('desc').value;
var newData2 = document.createElement('td');
newData2.innerHTML = document.getElementById('taskPriority').value;
var newData3 = document.createElement('td');
newData3.innerHTML = document.getElementById('taskDue').value;
myTable.appendChild(newRow);
newRow.appendChild(newData1);
newRow.appendChild(newData2);
newRow.appendChild(newData3);
var newData4 = document.createElement('td');
var delButton = document.createElement('input');
delButton.setAttribute('type', 'button');
delButton.setAttribute('name', 'deleteButton');
delButton.setAttribute('value', 'Delete');
newData4.appendChild(delButton);
newRow.appendChild(newData4);
}
}
function SomeDeleteRowFunction(btndel) {
if (typeof(btndel) == "object") {
$(btndel).closest("tr").remove();
} else {
return false;
}
}
try this code here is fiddle
alternatively try
//delete the table row
$(document).on('click', '#del', function(){
$(this).parents('tr').remove();
});
}); //del is the id of the delete block
one pure javascript approach
function deleteRowUI(btndel) {
var table=document.getElementById('filterTableBody');
if (typeof(btndel) == "object") {
p=btndel.parentNode.parentNode;
p.parentNode.removeChild(p);
var oTable = document.getElementById('filterTableBody');
//gets rows of table
var rowLength = oTable.rows.length;
for (var i = 1; i < rowLength; i++){
var oCells = oTable.rows.item(i).cells;
//gets cells of current row
var cellLength = oCells.length-1;
for(var j = 0; j < cellLength; j++){
oCells.item(j).innerHTML = "";
break;
}
break;
}
} else {
return false;
}
}
if you want to temporary hidden it you can do:
this.parentNode.style.display='none';
in mind that the exclusion button is in a td.
But if you want to really delete it from the html and the database:
you need to make the same as above and a extra call to a function of php/plsqlwathever to delete from de db, i recommend using ajax to call it.
http://www.w3schools.com/ajax/default.asp
uses jQuery remove method to do it.
By the id attribute :
$("#id here").remove();
By the class attribute :
$(".class name here").remove();
I hope I've helped a little...

why the onclick event doen't work from an external .js file?

I have wrote a .js file in wich I have create a table, buttons, etc. My aplication is a photo album and everything is created on this file, the html build up properly with all the buttons but when I give click on the buttons, the buttons don't change the images.
The code of the .jp file is:
var dp = document.createElement("img");
function changeImage()
{
var list = document.getElementById('optionlist');
dp.src = list.options[list.selectedIndex].value;
alert(dp.src);
}
function prevImage()
{
var list = document.getElementById('optionlist');
alert("Llega a prev");
if(list.selectedIndex == 0)
{
list.selectedIndex = list.options.length-1;
}
else
{
list.selectedIndex--;
}
changeImage();
}
function firstImage()
{
var list = document.getElementById('optionlist');
list.selectedIndex = 0;
changeImage();
}
function nextImage()
{
var list = document.getElementById('optionlist');
if(list.selectedIndex == list.options.length-1)
{
list.selectedIndex = 0;
}
else
{
list.selectedIndex++;
}
changeImage();
}
function lastImage()
{
var list = document.getElementById('optionlist');
list.selectedIndex = 9;
changeImage();
}
function start() {
var txt1,txt2,txt3,txt4,txt5,txt6,txt7,txt8,txt9,txt10,txt11;
//get the reference for the body
var body = document.getElementsByTagName("body")[0];
//alert("creates a <table> element and a <tbody> element");
var tbl = document.createElement("table");
tbl.setAttribute("align","center");
tbl.setAttribute("border","0");
var tbl2 = document.createElement("table");
tbl2.setAttribute("align","center");
tbl2.setAttribute("border","0");
var tblBody = document.createElement("tbody");
var tblBody2 = document.createElement("tbody");
//alert("creating <p>");
txt11 = document.createTextNode(" JavaScript Module ");
var downtxt = document.createElement("p");
downtxt.setAttribute("align","center");
downtxt.appendChild(txt11);
//alert("creates <input> elements");
var first = document.createElement("input");
first.setAttribute("value", " << ");
first.setAttribute("type", "button");
first.onClick = firstImage;
var previous = document.createElement("input");
previous.setAttribute("type", "button");
previous.setAttribute("value", " < ");
previous.onClick = "JavaScript:prevImage()";
var last = document.createElement("input");
last.setAttribute("value", " >> ");
last.setAttribute("type", "button");
last.onClick = "JavaScript:lastImage()";
var next = document.createElement("input");
next.setAttribute("value", " > ");
next.setAttribute("type", "button");
next.onClick = "JavaScript:nextImage()";
//alert("creating images options and <select>");
var op1 = document.createElement("option");
var op2 = document.createElement("option");
var op3 = document.createElement("option");
var op4 = document.createElement("option");
var op5 = document.createElement("option");
var op6 = document.createElement("option");
var op7 = document.createElement("option");
var op8 = document.createElement("option");
var op9 = document.createElement("option");
var op10 = document.createElement("option");
op1.setAttribute("value","1.jpg");
txt1 = document.createTextNode("First Image");
op1.appendChild(txt1);
op2.setAttribute("value","2.jpg");
txt2 = document.createTextNode("Second Image");
op2.appendChild(txt2);
op3.setAttribute("value","3.jpg");
txt3 = document.createTextNode("Third Image");
op3.appendChild(txt3);
op4.setAttribute("value","4.jpg");
txt4 = document.createTextNode("Fourth Image");
op4.appendChild(txt4);
op5.setAttribute("value","5.jpg");
txt5 = document.createTextNode("Fifth Image");
op5.appendChild(txt5);
op6.setAttribute("value","6.jpg");;
txt6 = document.createTextNode("Sixth Image");
op6.appendChild(txt6);
op7.setAttribute("value","7.jpg");
txt7 = document.createTextNode("Seventh Image");
op7.appendChild(txt7);
op8.setAttribute("value","8.jpg");
txt8 = document.createTextNode("Eight Image");
op8.appendChild(txt8);
op9.setAttribute("value","9.jpg");
txt9 = document.createTextNode("Ninth Image");
op9.appendChild(txt9);
op10.setAttribute("value","10.jpg");
txt10 = document.createTextNode("Tenth Image");
op10.appendChild(txt10);
var slct = document.createElement("select");
slct.setAttribute("id","optionlist");
slct.onChange = changeImage;
slct.appendChild(op1);
slct.appendChild(op2);
slct.appendChild(op3);
slct.appendChild(op4);
slct.appendChild(op5);
slct.appendChild(op6);
slct.appendChild(op7);
slct.appendChild(op8);
slct.appendChild(op9);
slct.appendChild(op10);
//alert("Creating rows and columns for the tables");
var td1 = document.createElement("td");
td1.setAttribute("align","center");
td1.setAttribute("colspan","3");
dp.setAttribute("name","mainimage");
dp.setAttribute("border","1");
dp.setAttribute("align","center");
td1.appendChild(dp);
var tr1 = document.createElement("tr");
tr1.setAttribute("align","center");
tr1.appendChild(td1);
var td2 = document.createElement("td");
td2.setAttribute("align","left");
td2.appendChild(first);
td2.appendChild(previous);
var td3 = document.createElement("td");
td3.setAttribute("align","center");
td3.appendChild(slct);
var td4 = document.createElement("td");
td4.setAttribute("align","right");
td4.appendChild(next);
td4.appendChild(last);
var tr2 = document.createElement("tr");
tr2.appendChild(td2);
tr2.appendChild(td3);
tr2.appendChild(td4);
//alert("adding all the elements to the table");
tblBody2.appendChild(tr1);
tblBody.appendChild(tr2);
tbl2.appendChild(tblBody2);
tbl.appendChild(tblBody);
//alert("adding table to <body>");
body.appendChild(tbl2);
body.appendChild(tbl);
body.appendChild(downtxt);
changeImage();
}
and the html code is:
<html>
<head>
<title>Photo Album </title>
<style>
p, td {color:blue;font-family:verdana;font-size:8pt}
h1 {color:black;font-family:verdana;font-size:14pt}
</style>
<script type = "text/javascript" src = "PAScript.js" language = "javascript">
</script>
</head>
<body onLoad="start()" bgcolor = "grey">
</body>
</html>
It somebody can help me please, I don't have idea how to make work the buttons of my application
Thanks
When you're setting onclick by javascript, it's a function reference instead of a string.
previous.onClick = "JavaScript:prevImage()";
should be
previous.onclick = prevImage;
Fix your other assignments to follow this pattern. Also onclick is all lower case and is case sensitive.
As long as we're on the topic, the preferred way to register event handlers is
standards compliant browsers
previous.addEventListener('click', prevImage, false);
IE
previous.attachEvent('onclick', prevImage);

Categories

Resources