I cant get data from this getElementbyId - javascript

HTML part... a To do list with 4 properties: the property "description" its not to be shown on the table. But when you dbclick on first cell(title), it should return all the 4 properties.
<body>
<h1 id="h1">ToDo Lijst</h1>
<label for="item">Titel</label><br>
<input type="text" id = "Item"><br><br>
<!--<p style="color:red; font-size:18px;" id="FoutInput"></p>-->
<label for = "aantal">Omschrijving</label><br>
<input class="desc" type="text" id="description"><br><br>
<label for="person">Toegewezen Person</label><br>
<input type="text" id = "person"><br><br>
<label for="deadline">Deadline</label><br>
<input type="text" id="deadline">
<button type = "button" onclick="Toevoegen()"><span>+</span></button>
<button type="button" onclick="Edit()" >Aanpassen</button>
<button style="background-color: crimson" onclick="Verwijderen()"><i class="fa fa-trash-o"></i></button>
<p style="color:red; font-size:15px;" id="FoutInput"></p>
<table id="table">
<tr>
<th>Titel</th>
<th>Toegewezen Person</th>
<th>Deadline</th>
</tr>
</table>
//javascript part
var rIndex,
table = document.getElementById("table");
function Toevoegen()
{
var newrow = table.insertRow(table.length),
cell1 = newrow.insertCell(0),
cell2=newrow.insertCell(1),
cell3=newrow.insertCell(2),
Titel = document.getElementById("Item").value,
person = document.getElementById("person").value,
deadline = document.getElementById("deadline").value;
//var description = document.getElementById("description").value;
if(Titel != "" && person != "" && deadline != "")
{
cell1.innerHTML = Titel;
cell2.innerHTML = person;
cell3.innerHTML = deadline;
document.getElementById("Item").value = ""; document.getElementById("person").value = "";
document.getElementById("deadline").value = "";
document.getElementById("description").value = "";
console.log(description);
var text1 = "Toegevoegd!";
document.getElementById("FoutInput").innerHTML = text1;
}
else{
cell1 = newrow.deleteCell(0);
cell2 = newrow.deleteCell(0,1);
var text = "Veld(en) mag(mogen) niet leeg blijven!";
document.getElementById("FoutInput").innerHTML = text;
}
selectedRowtoinput();
selectedCell();
}
function selectedCell(){
for(var i = 1;i<table.rows.length; i++){
table.rows[i].cells[0].ondblclick = function(){
var titel = document.getElementById("Item").value;
var person = document.getElementById("person").value;
var deadline = document.getElementById("deadline").value;
var description =
document.getElementById("description").value;
console.log(description);
alert("overzicht:" + "\n" + titel+ "\n" + person+ "\n" + deadline + "\n" + "omschrijving: " + description);
}
}
}
function selectedRowtoinput()
{
for(var i =1; i< table.rows.length; i++)
{
table.rows[i].onclick = function()
{
rIndex = this.rowIndex;
document.getElementById("Item").value =this.cells[0].innerHTML;
document.getElementById("person").value =this.cells[1].innerHTML;
document.getElementById("deadline").value =this.cells[2].innerHTML;
}
}
}
selectedRowtoinput();
I cant get data from:
var description =
document.getElementById("description").value;
console.log(description);
I just get an empty line. I get the info from the other 3 except this one...

Ok, I've updated your code and alter it with logic, that you DO create cell for description, but make in hidden, so it is not visible, but still holds the data, check example
var rIndex,
table = document.getElementById("table");
function Toevoegen()
{
var newrow = table.insertRow(table.length),
cell1 = newrow.insertCell(0),
cell2=newrow.insertCell(1),
cell3=newrow.insertCell(2),
cell4=newrow.insertCell(3),
Titel = document.getElementById("Item").value,
person = document.getElementById("person").value,
deadline = document.getElementById("deadline").value,
description = document.getElementById("description").value;
// Make hidden cell for description
cell4.className += " hidden";
if(Titel != "" && person != "" && deadline != "")
{
cell1.innerHTML = Titel;
cell2.innerHTML = person;
cell3.innerHTML = deadline;
// Put data in hidden cell
cell4.innerHTML = description;
document.getElementById("Item").value = "";
document.getElementById("person").value = "";
document.getElementById("deadline").value = "";
document.getElementById("description").value = "";
var text1 = "Toegevoegd!";
document.getElementById("FoutInput").innerHTML = text1;
}
else{
cell1 = newrow.deleteCell(0);
cell2 = newrow.deleteCell(0,1);
var text = "Veld(en) mag(mogen) niet leeg blijven!";
document.getElementById("FoutInput").innerHTML = text;
}
selectedRowtoinput();
selectedCell();
}
function selectedCell(){
for(var i = 1;i<table.rows.length; i++){
table.rows[i].cells[0].ondblclick = function(){
var titel = document.getElementById("Item").value;
var person = document.getElementById("person").value;
var deadline = document.getElementById("deadline").value;
var description = document.getElementById("description").value;
alert("overzicht:" + "\n" + titel+ "\n" + person+ "\n" + deadline + "\n" + "omschrijving: " + description);
}
}
}
function selectedRowtoinput()
{
for(var i =1; i< table.rows.length; i++)
{
table.rows[i].onclick = function()
{
rIndex = this.rowIndex;
document.getElementById("Item").value = this.cells[0].innerHTML;
document.getElementById("person").value = this.cells[1].innerHTML;
document.getElementById("deadline").value = this.cells[2].innerHTML;
document.getElementById("description").value = this.cells[3].innerHTML;
}
}
}
selectedRowtoinput();
.hidden {
display: none;
}
<body>
<h1 id="h1">ToDo Lijst</h1>
<label for="item">Titel</label><br>
<input type="text" id = "Item"><br><br>
<!--<p style="color:red; font-size:18px;" id="FoutInput"></p>-->
<label for = "aantal">Omschrijving</label><br>
<input class="desc" type="text" id="description"><br><br>
<label for="person">Toegewezen Person</label><br>
<input type="text" id = "person"><br><br>
<label for="deadline">Deadline</label><br>
<input type="text" id="deadline">
<button type = "button" onclick="Toevoegen()"><span>+</span></button>
<button type="button" onclick="Edit()" >Aanpassen</button>
<button style="background-color: crimson" onclick="Verwijderen()"><i class="fa fa-trash-o"></i></button>
<p style="color:red; font-size:15px;" id="FoutInput"></p>
<table id="table">
<tr>
<th>Titel</th>
<th>Toegewezen Person</th>
<th>Deadline</th>
</tr>
</table>

Related

How to get table row value into text field in JavaScript..?

I Create a Table Using this code,
<table class="table table-green table-hover" id="tblk"></table>
And I Use This JavaScrip Function (For A Button) to add Rows when I add data in to table,
function addRow() {
var custid = document.getElementById('InputCusomerID').value
var custname = document.getElementById('InputCusomerName').value
var itemid = document.getElementById('InputItemID').value
var table = document.getElementById('tblk')
var row = table.insertRow(0)
var cell1 = row.insertCell(0)
var cell2 = row.insertCell(1)
var cell3 = row.insertCell(2)
cell1.innerHTML = custid
cell2.innerHTML = custname
cell3.innerHTML = itemid
}
When I clicked a table row, I need to get a table Row value into my input text field
This Is my JavaScrip Function to get table rows to value into my text field..,
var table = document.getElementById('tblk'),
rIndex
for (var i = 1; i < table.rows.length; i++) {
table.rows[i].onclick = function () {
document.getElementById('InputCusomerID').value = this.cells[0].innerHTML
document.getElementById('InputCusomerName').value = this.cells[1].innerHTML
document.getElementById('InputItemID').value = this.cells[2].innerHTML
}
}
But My Code Is Not Working I Can't Get Table Row Value Into My Text Field.
Can You Help Me With That Problem..?
Thank You Very Much..!
function addRow() {
var custid = document.getElementById('InputCusomerID').value
var custname = document.getElementById('InputCusomerName').value
var itemid = document.getElementById('InputItemID').value
var table = document.getElementById('tblk')
var row = table.insertRow(0)
var cell1 = row.insertCell(0)
var cell2 = row.insertCell(1)
var cell3 = row.insertCell(2)
cell1.innerHTML = custid
cell2.innerHTML = custname
cell3.innerHTML = itemid
}
var table = document.getElementById('tblk'),
rIndex
for (var i = 1; i < table.rows.length; i++) {
table.rows[i].onclick = function() {
document.getElementById('InputCusomerID').value = this.cells[0].innerHTML
document.getElementById('InputCusomerName').value = this.cells[1].innerHTML
document.getElementById('InputItemID').value = this.cells[2].innerHTML
}
}
<table class="table table-green table-hover" id="tblk"></table>
I don't know exactly what you're trying to do, but it's not working because your click listener is being called before your table is populated. See my code.
function addRow() {
var custid = document.getElementById('InputCusomerID').value
var custname = document.getElementById('InputCusomerName').value
var itemid = document.getElementById('InputItemID').value
var table = document.getElementById('tblk')
var row = table.insertRow(0)
var cell1 = row.insertCell(0)
var cell2 = row.insertCell(1)
var cell3 = row.insertCell(2)
cell1.innerHTML = custid
cell2.innerHTML = custname
cell3.innerHTML = itemid
setListeners();
}
var table = document.getElementById('tblk'),
rIndex;
function setListeners() {
for (var i = 0; i < table.rows.length; i++) {
table.rows[i].addEventListener('click', function (e) {
console.log(e.target);
document.getElementById('InputCusomerID').value = "result: " + this.cells[0].innerHTML
document.getElementById('InputCusomerName').value = "result: " + this.cells[1].innerHTML
document.getElementById('InputItemID').value = "result: " + this.cells[2].innerHTML
});
}
}
addRow();
<input type="text" id="InputCusomerID" value="a" />
<input type="text" id="InputCusomerName" value="b" />
<input type="text" id="InputItemID" value="c" />
<table class="table table-green table-hover" id="tblk"></table>

How to embed button with Vue code into cell inserted with insertCell()?

I have Vue component with a table with users data:
<table class="worker-table" id="worker-table">
<tr>
<th><b>Phone number</b></th>
<th><b>Debet card</b></th>
<th><b>Money</b></th>
<th><b>Work hours</b></th>
<th><b>Responsible</b></th>
<th><b>Delete</b></th>
</tr>
<tr>
<tr v-for="worker in workers">
<td >
<div v-if="worker.parent == 1">
<strong v-on:click="toggleChildWorkers(worker)" class="pointer">
{{worker.phone}}(+{{child_workers[worker.id].length}})
</strong>
</div>
<div v-else>
{{worker.phone}}
</div>
</td>
<td>{{worker.debit_card}}</td>
<td>{{worker.money}}</td>
<td>{{worker.work_hours}}</td>
<td>{{worker.responsible_for_money}}</td>
<td>
<a href="#"
v-bind:disabled="(application.state > CLOSED_ST)? true: false"
class="btn btn-xs btn-danger"
v-on:click="deleteEntry(worker.id)"
>
Delete
</a>
</td>
</tr>
</table>
The button in the last <td> successfully deletes worker from the table.
Function toggleChildWorkers insert new rows with child workers and delete (hide, actually) them like this:
toggleChildWorkers(parentWorker)
{
var table = document.getElementById("worker-table");
var childWorkers = this.child_workers[parentWorker.id];
var childWorkersCount = childWorkers.length;
var parentWorkersIndexes = this.openAccordionsIndexes;
var dI = 0;
var userWantsCloseThisAccordion = false;
var indexOfClosingAcc = -1;
console.log(parentWorker);
for (var j = 0; j < parentWorkersIndexes.length; j++)
{
if (parentWorkersIndexes[j] < parentWorker.index)
{
dI += this.openAccordionsStrCount[j];
}
else if (parentWorkersIndexes[j] == parentWorker.index)
{
userWantsCloseThisAccordion = true;
indexOfClosingAcc = j;
}
}
if (userWantsCloseThisAccordion)
{
for (var i = 0; i < this.openAccordionsStrCount[indexOfClosingAcc]; i++)
{
table.deleteRow(parentWorker.index + 3 + dI);
}
this.openAccordionsIndexes.splice(indexOfClosingAcc, 1);
this.openAccordionsStrCount.splice(indexOfClosingAcc, 1);
return;
}
this.openAccordionsIndexes.push(parentWorker.index);
this.openAccordionsStrCount.push(childWorkersCount);
for (var i = 0; i < childWorkersCount; i++)
{
var row = table.insertRow(parentWorker.index + 3 + dI + i);
var cell1 = row.insertCell(0);
cell1.style.cssText = this.styleOfOpenAccStrings;
var cell2 = row.insertCell(1);
cell2.style.cssText = this.styleOfOpenAccStrings;
var cell3 = row.insertCell(2);
cell3.style.cssText = this.styleOfOpenAccStrings;
var cell4 = row.insertCell(3);
cell4.style.cssText = this.styleOfOpenAccStrings;
var cell5 = row.insertCell(4);
cell5.style.cssText = this.styleOfOpenAccStrings;
var cell6 = row.insertCell(5);
cell6.style.cssText = this.styleOfOpenAccStrings;
cell1.innerHTML = (childWorkers[i].phone === undefined) ?
'' : childWorkers[i].phone;
cell2.innerHTML = (childWorkers[i].debit_card === undefined) ?
'' : childWorkers[i].debit_card;
cell3.innerHTML = (childWorkers[i].money === undefined) ?
'' : childWorkers[i].money;
cell4.innerHTML = (childWorkers[i].work_hours === undefined) ?
'' : childWorkers[i].work_hours;
cell5.innerHTML = childWorkers[i].responsible_for_money;
cell6.innerHTML = "<a href=\"#\"\n" +
" v-bind:disabled=\"(application.state > CLOSED_ST)? true: false\"\n" +
" class=\"btn btn-xs btn-danger\"\n" +
" v-on:click=\"deleteEntry(props.row.index)\"\n" +
" >";
row.className = "openAccordionRow";
}
},
As you can see, I'm trying to embed buttons in the new cells of inserted rows (blue ones). But they are not displayed as it was intended and don't work at all.
How can I embed button with Vue code into new cell of inserted row?
I found a simple solution here. But I did't understand it at the beginning and use it without closure and it did't work as I expected. Then I found topic about Javascript infamous loop issue
and used the closure magic:
for (var i = 0; i < childWorkersCount; i++)
{
/* ...
...
...
*/
var btn = document.createElement('input');
btn.type = "button";
btn.className = "btn btn-xs btn-danger";
btn.value = "Delete " + childWorkers[i].phone;
var app = this;
var parentId = parentWorker.id;
btn.onclick = function (worker) {
return function () {
app.deleteEntryById(worker.id, parentId);
};
}(childWorkers[i]);
}

Need help updating the index for selected row

I have been stuck on an issue where I am trying to use Javascript to add and remove a row from a table.
I got the add part working, the delete somewhat. The delete fails if you delete the first row or a row in the middle (live code can be seen here
I uploaded its code on PasteBin
<script type="text/javascript">
var itemNumber = 0
var currentRow = 0;
var selectedRow = 0;
function theIndex(theRow){
selectedRow = theRow;
}
document.getElementById("addItem").addEventListener("click", function(){
if (document.getElementById('whatToDo').value != ""){
currentRow++;
var table = document.getElementById('myList');
var row = table.insertRow(currentRow);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
itemNumber++;
// alert(currentRow);
// cell1.innerHTML = itemNumber;
cell2.innerHTML = document.getElementById('whatToDo').value;
cell3.innerHTML = document.getElementById('whenToDo').value;
cell4.innerHTML = document.getElementById('whereToDo').value;
row.addEventListener('click', theIndex.bind(null, currentRow));
document.getElementById('whatToDo').value = "";
document.getElementById('whenToDo').value = "";
document.getElementById('whereToDo').value = "";
}
});
document.getElementById("removeItem").addEventListener("click", function(){
// var theRow = document.getElementById('whatToMark').value;
var theRow = selectedRow;
alert("index: " +theRow + " elements: " + currentRow);
if (theRow > 0){
document.getElementById("myList").deleteRow(theRow);
document.getElementById('whatToMark').value = "";
currentRow--;
itemNumber--;
}
selectedRow = 0;
});
document.getElementById("markAsDone").addEventListener("click", function(){
// var theRow = document.getElementById('whatToMark').value;
var theRow = selectedRow;
alert("index: " +theRow + " elements: " + currentRow);
var table = document.getElementById('myList');
if (theRow != 0){
table.rows[theRow].style.setProperty("text-decoration", "line-through");
document.getElementById('whatToMark').value = "";
}
selectedRow = 0;
});
</script>
I am learning Javascript and wanted to do more than the exercise that was being given by adding new features to it.
Your approach to mark the current selected row has some issues:
row.addEventListener('click', theIndex.bind(null, currentRow));
Instead of using a global variable I suggest to use a row attribute (or class). Hence, change that line to:
row.addEventListener('click', function(e) {
document.querySelectorAll('tr[selected]').forEach(function(item) {
item.removeAttr('selected');
})
row.setAttribute('selected', true);
});
Add the attribute selected for the current row and remove the same attribute for other rows.
In this way, when you need to get the current selected row you can simply:
var rSelected = document.querySelector('tr[selected]');
var theRow = (rSelected == null) ? 0 : rSelected.rowIndex;
var itemNumber = 0
var currentRow = 0;
var selectedRow = 0;
function theIndex(theRow) {
selectedRow = theRow;
}
document.getElementById("addItem").addEventListener("click", function () {
if (document.getElementById('whatToDo').value != "") {
currentRow++;
var table = document.getElementById('myList');
var row = table.insertRow(currentRow);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
itemNumber++;
// alert(currentRow);
// cell1.innerHTML = itemNumber;
cell2.innerHTML = document.getElementById('whatToDo').value;
cell3.innerHTML = document.getElementById('whenToDo').value;
cell4.innerHTML = document.getElementById('whereToDo').value;
//row.addEventListener('click', theIndex.bind(null, currentRow));
row.addEventListener('click', function(e) {
document.querySelectorAll('tr[selected]').forEach(function(item) {
item.removeAttr('selected');
})
row.setAttribute('selected', true);
});
document.getElementById('whatToDo').value = "";
document.getElementById('whenToDo').value = "";
document.getElementById('whereToDo').value = "";
}
});
document.getElementById("removeItem").addEventListener("click", function () {
// var theRow = document.getElementById('whatToMark').value;
var rSelected = document.querySelector('tr[selected]');
var theRow = (rSelected == null) ? 0 : rSelected.rowIndex;
if (theRow > 0) {
document.getElementById("myList").deleteRow(theRow);
//document.getElementById('whatToMark').value = "";
currentRow--;
itemNumber--;
}
selectedRow = 0;
});
document.getElementById("markAsDone").addEventListener("click", function () {
// var theRow = document.getElementById('whatToMark').value;
var theRow = selectedRow;
alert("index: " + theRow + " elements: " + currentRow);
var table = document.getElementById('myList');
if (theRow != 0) {
table.rows[theRow].style.setProperty("text-decoration", "line-through");
document.getElementById('whatToMark').value = "";
}
selectedRow = 0;
});
<div class="container">
<div class="row">
<div class="col-lg-4 col-sm-6">
<table class="table table-hover">
<tr>
<td colspan="3">
<h1>To Do List Example</h1>
</td>
</tr>
<tr>
<th><label>Item</label></th>
<th><label>Date</label></th>
<th><label>Location</label></th>
</tr>
<tr>
<td>
<input type="text" id="whatToDo" value="">
</td>
<td>
<input type="date" id="whenToDo" value="">
</td>
<td>
<input type="text" id="whereToDo" value="">
</td>
</tr>
<tr>
<td>
<button id="addItem" class="btn btn-default btn-primary active">
<i class="fas fa-plus"></i> Add This Item
</button>
</td>
<td>
<button id="markAsDone" class="btn btn-default ">
<i class="fas fa-check"></i> Mark As Done
</button>
</td>
<td>
<button id="removeItem" class="btn btn-default">
<i class="fas fa-trash-alt"></i> Remove Item
</button>
</td>
</tr>
</table>
</div>
</div>
<div class="row">
<div class="col-lg-4 col-sm-6">
<table class="table table-hover" id="myList">
<tr>
<th><label></label></th>
<th><label>Event</label></th>
<th><label>Date</label></th>
<th><label>Location</label></th>
</tr>
</table>
</div>
</div>
</div>
This line is throwing a null value error:
document.getElementById('whatToMark').value = "";
Neither in your JS, nor in your HTML, do you ever set an element to the ID of whatToMark.

clear button is clearing all the values in the body ? update button is add another row with out updating the given value?

here clear button is not working in javascript?
var a = [];
var index = "";
document.getElementById("update").style.display = "none";
function add(){
var firstname = document.getElementById("firstname").value;
var lastname = document.getElementById("lastname").value;
var age = document.getElementById("age").value;
document.getElementById("firstname").value = "";
document.getElementById("lastname").value = "";
document.getElementById("age").value = "";
function clear(){
document.getElementById("firstname").value = "";
document.getElementById("lastname").value = "";
document.getElementById("age").value = "";
}
if ((firstname == "" || lastname == "" || age == ""))
{
alert ("Enter all the textbox values");
}else{
var person = {fname:firstname,lname:lastname,ag:age};
if(index != ''|| index ==' ')
{
document.getElementById("add").style.display = "inline";
document.getElementById("update").style.display = "inline";
a[index] = person;
index ='';
}else{
a.push(person);
}
document.getElementById("update").style.display = "none";
add_details();
}
}
function add_details(){
var table = "";
var row = a.length
for (i=0;i<a.length;i++){
table += "<tr>";
table += "<td>"+a[i].fname+"</td>";
table += "<td>"+a[i].lname+"</td>"
table += "<td>"+a[i].ag+"</td>";
table += "<td><button onclick = 'edit("+i+")' id = 'edit'>Edit</button></td>";
table += "<td><button onclick = 'deletedetails("+i+")'id = 'delete'>Delete</button></td>";
table += "</tr>";
}
document.getElementById("arraytable").innerHTML = table;
}
function edit(t){
index = t;
document.getElementById("add").style.display = "none";
document.getElementById("update").style.display = "inline";
document.getElementById("firstname").value= a[t].fname;
document.getElementById("lastname").value= a[t].lname;
document.getElementById("age").value= a[t].ag;
add_details();
}
function deletedetails(i){
a.splice(i,1);
add_details();
}
<h1>Students Form</h1>
FirstName :<input type = "text" id = "firstname" value = "" required> <br>
LastName :<input type = "text" id = "lastname" value = "" required> <br>
Age :<input type = "number"id="age" value = "" required><br><br>
<button id = "add" onclick = "add()">Add</button>
<button id = "update" onclick = "add()">Update</button>
<button id = "clear" onclick = "clear()">Clear</button> <br><br>
<table border = "1" >
<th>FirstName</th>
<th>LastName</th>
<th>Age</th>
<th>Edit</th>
<th>Delete</th>
<tbody id = "arraytable"></tbody>
</table>
var firstname = "";
var lastname = "";
var age = "";
//var gender = "";
var a = [];
var ind = "";
var newfname = "";
var newlname = "";
var newage = "";
//var newgender = "";
var table = "";
function add()
{
if ((firstname == "" || lastname == "" || age == ""))
{
alert ("Enter all the textbox values");
}
//document.getElementById("tbhide").style.display="none";
firstname =document.getElementById("firstname").value;
lastname =document.getElementById("lastname").value;
//gender = document.getElementByName("gender").value;
age = document.getElementById("age").value;
document.getElementById("firstname").value = "" ;
document.getElementById("lastname").value = "";
//document.getElementByName("gender").value = "";
document.getElementById("age").value = "";
var person = {fname:firstname,lname:lastname,ag:age}
if(ind != '')
{
document.getElementById("add").style.display = "none";
b.style.display = "inline";
a[ind] = person;
}else{
a.push(person);
}
adddet();
}
function adddet(){
var table = '';
var rows = a.length;
for( i =0;i<rows; i++){
table+="<tr>";
table+="<td>"+a[i].fname+"</td>";
table+="<td>"+a[i].lname+"</td>";
table+="<td>"+a[i].ag+"</td>";
//table+="<td>"+a[i].gender+"</td>";
table+="<td><button onClick='edit("+i+")'>Edit</button></td>";
table+="<td><button onClick='deleterow("+i+")'>Delete</button></td>";
table+="<tr>";
}
document.getElementById("arraytable").innerHTML = table;
}
function edit(i){
ind = i;
document.getElementById("add").style.display = "none";
document.getElementById("update").style.display = "inline";
document.getElementById("firstname").value= a[ind].fname;
document.getElementById("lastname").value= a[ind].lname;
document.getElementById("age").value= a[ind].ag;
//document.getElementByName("gender").value = a[ind].gender;
}
function deleterow(i){
a.splice(i,1);
adddet();
}
function clear(){
document.getElementById("firstname").value= "";
document.getElementById("lastname").value="";
document.getElementById("age").value="";
//document.getElementByName("gender").value="";
}
var b = document.getElementById("update");
console.log(b);
b.style.display ="none";
var d = document.getElementById("add");
var e = document.getElementById("tbhide");
//document.getElementById("tbhide").style.display="none";
<form>
FirstName : <input type = "text" id = "firstname" value = "" required> <br>
LastName : <input type = "text" id = "lastname" value = "" required> <br>
age : <input type = "number" id = "age" value = "" required> <br><br>
<!--Male : <input type="radio" name = "gender" value = "male">
Female:<input type="radio" name = "gender" value = "female"><br>-->
<button id = "clear" onclick="clear()">Clear</button>
</form>
<button type = "submit" id = "add" onclick = "add()" >Add</button>
<button id = "update" onclick = "add()" >Update</button>
<table border = "1" id = "tbhide">
<th>FirstName</th>
<th>LastName</th>
<th>Age</th>
<!--<th>Gender</th>-->
<th>Edit</th>
<th>Delete</th>
<tbody id = "arraytable"></tbody>
</table>
all properties are working but clear button is not working . if i keep form tag also it is not working
var a = [];
var index = "";
document.getElementById("update").style.display = "none";
function add(){
var firstname = document.getElementById("firstname").value;
var lastname = document.getElementById("lastname").value;
var age = document.getElementById("age").value;
document.getElementById("firstname").value = "";
document.getElementById("lastname").value = "";
document.getElementById("age").value = "";
function clear(){
document.getElementById("firstname").value = "";
document.getElementById("lastname").value = "";
document.getElementById("age").value = "";
}
if ((firstname == "" || lastname == "" || age == ""))
{
alert ("Enter all the textbox values");
}else{
var person = {fname:firstname,lname:lastname,ag:age};
if(index != ''|| index ==' ')
{
document.getElementById("add").style.display = "inline";
document.getElementById("update").style.display = "inline";
a[index] = person;
index ='';
}else{
a.push(person);
}
document.getElementById("update").style.display = "none";
add_details();
}
}
FirstName :<input type = "text" id = "firstname" value = "" required> <br>
LastName :<input type = "text" id = "lastname" value = "" required> <br>
Age :<input type = "number"id="age" value = "" required><br><br>
<button id = "add" onclick = "add()">Add</button>
<button id = "update" onclick = "add()">Update</button>
<button id = "clear" onclick = "clear()">Clear</button> <br><br>
<table border = "1" >
<th>FirstName</th>
<th>LastName</th>
<th>Age</th>
<th>Edit</th>
<th>Delete</th>
<tbody id = "arraytable"></tbody>
clear button is not working if we keep form tag also it is not wroking can any one help
Instead of using forloop and index, you can use child/parent relationship to get the element you want to edit or delete etc.. This is not a full answer, rather an example that should hopefully give you an idea of how to achieve what you're wanting to achieve.
function deleteRow(btn) {
var row = btn.parentNode.parentNode;
row.parentNode.removeChild(row);
}
function add() {
var table = document.getElementById("dsTable");
var newRow = table.innerHTML;
newRow = newRow += "<tr>";
newRow += "<td>" + "a[i].fname" + "</td>";
newRow += "<td>" + "a[i].lname" + "</td>";
newRow += "<td>" + "a[i].ag" + "</td>";
//table+="<td>"+a[i].gender+"</td>";
newRow += "<td><button type='submit' id='delete' onclick='deleteRow(this)'>Delete</button></td>";
table.innerHTML = newRow;
}
<input type="button" value="Add" onclick="add()"/>
<table id="dsTable">
<tbody>
<tr>
<td>header</td>
<td>header</td>
<td>header</td>
</tr>
<tr>
<td>test</td>
<td>test</td>
<td>test</td>
<td><input type="button" value="Delete" onclick="deleteRow(this)"/></td>
</tr>
<tr>
<td>test</td>
<td>test</td>
<td>test</td>
<td><input type="button" value="Delete" onclick="deleteRow(this)"/></td>
</tr>
</tbody>
</table>
In your add() function you can add a conditon that check what's action was executed.
function add(flag) {
....
....
if(!flag) {
adddet();
} else {
document.getElementById("fn"+ind).innerHTML = a[ind].fname;
document.getElementById("ln"+ind).innerHTML = a[ind].lname;
document.getElementById("ag"+ind).innerHTML = a[ind].ag;
}
}
In your adddet() function you can give id's our td's to access the values of row by id.
function adddet(){
...
...
table+="<td id='fn"+i+"'>"+a[i].fname+"</td>";
table+="<td id='ln"+i+"'>"+a[i].lname+"</td>";
table+="<td id='ag"+i+"'>"+a[i].ag+"</td>";
...
...
}
In your html, pass as argument the flag that will say if the action is
add or update.
<button type = "submit" id = "add" onclick = "add(false)" >Add</button>
<button id = "update" onclick = "add(true)" >Update</button>
I hope this useful for you !

Dynamic creation of table with DOM

Can someone tell me what's wrong with this code? I want to create a table with 2 columns and 3 rows, and in the cells I want Text1 and Text2 on every row. This code creates a table with 2 columns and 3 rows, but it's only text in the cells in the third row (the others are empty).
var tablearea = document.getElementById('tablearea');
var table = document.createElement('table');
var tr = [];
var td1 = document.createElement('td');
var td2 = document.createElement('td');
var text1 = document.createTextNode('Text1');
var text2 = document.createTextNode('Text2');
for (var i = 1; i < 4; i++){
tr[i] = document.createElement('tr');
for (var j = 1; j < 4; j++){
td1.appendChild(text1);
td2.appendChild(text2);
tr[i].appendChild(td1);
tr[i].appendChild(td2);
}
table.appendChild(tr[i]);
}
tablearea.appendChild(table);
You must create td and text nodes within loop. Your code creates only 2 td, so only 2 are visible. Example:
var table = document.createElement('table');
for (var i = 1; i < 4; i++){
var tr = document.createElement('tr');
var td1 = document.createElement('td');
var td2 = document.createElement('td');
var text1 = document.createTextNode('Text1');
var text2 = document.createTextNode('Text2');
td1.appendChild(text1);
td2.appendChild(text2);
tr.appendChild(td1);
tr.appendChild(td2);
table.appendChild(tr);
}
document.body.appendChild(table);
It is because you're only creating two td elements and 2 text nodes.
Creating all nodes in a loop
Recreate the nodes inside your loop:
var tablearea = document.getElementById('tablearea'),
table = document.createElement('table');
for (var i = 1; i < 4; i++) {
var tr = document.createElement('tr');
tr.appendChild( document.createElement('td') );
tr.appendChild( document.createElement('td') );
tr.cells[0].appendChild( document.createTextNode('Text1') )
tr.cells[1].appendChild( document.createTextNode('Text2') );
table.appendChild(tr);
}
tablearea.appendChild(table);
Creating then cloning in a loop
Create them beforehand, and clone them inside the loop:
var tablearea = document.getElementById('tablearea'),
table = document.createElement('table'),
tr = document.createElement('tr');
tr.appendChild( document.createElement('td') );
tr.appendChild( document.createElement('td') );
tr.cells[0].appendChild( document.createTextNode('Text1') )
tr.cells[1].appendChild( document.createTextNode('Text2') );
for (var i = 1; i < 4; i++) {
table.appendChild(tr.cloneNode( true ));
}
tablearea.appendChild(table);
Table factory with text string
Make a table factory:
function populateTable(table, rows, cells, content) {
if (!table) table = document.createElement('table');
for (var i = 0; i < rows; ++i) {
var row = document.createElement('tr');
for (var j = 0; j < cells; ++j) {
row.appendChild(document.createElement('td'));
row.cells[j].appendChild(document.createTextNode(content + (j + 1)));
}
table.appendChild(row);
}
return table;
}
And use it like this:
document.getElementById('tablearea')
.appendChild( populateTable(null, 3, 2, "Text") );
Table factory with text string or callback
The factory could easily be modified to accept a function as well for the fourth argument in order to populate the content of each cell in a more dynamic manner.
function populateTable(table, rows, cells, content) {
var is_func = (typeof content === 'function');
if (!table) table = document.createElement('table');
for (var i = 0; i < rows; ++i) {
var row = document.createElement('tr');
for (var j = 0; j < cells; ++j) {
row.appendChild(document.createElement('td'));
var text = !is_func ? (content + '') : content(table, i, j);
row.cells[j].appendChild(document.createTextNode(text));
}
table.appendChild(row);
}
return table;
}
Used like this:
document.getElementById('tablearea')
.appendChild(populateTable(null, 3, 2, function(t, r, c) {
return ' row: ' + r + ', cell: ' + c;
})
);
You need to create new TextNodes as well as td nodes for each column, not reuse them among all of the columns as your code is doing.
Edit:
Revise your code like so:
for (var i = 1; i < 4; i++)
{
tr[i] = document.createElement('tr');
var td1 = document.createElement('td');
var td2 = document.createElement('td');
td1.appendChild(document.createTextNode('Text1'));
td2.appendChild(document.createTextNode('Text2'));
tr[i].appendChild(td1);
tr[i].appendChild(td2);
table.appendChild(tr[i]);
}
<title>Registration Form</title>
<script>
var table;
function check() {
debugger;
var name = document.myForm.name.value;
if (name == "" || name == null) {
document.getElementById("span1").innerHTML = "Please enter the Name";
document.myform.name.focus();
document.getElementById("name").style.border = "2px solid red";
return false;
}
else {
document.getElementById("span1").innerHTML = "";
document.getElementById("name").style.border = "2px solid green";
}
var age = document.myForm.age.value;
var ageFormat = /^(([1][8-9])|([2-5][0-9])|(6[0]))$/gm;
if (age == "" || age == null) {
document.getElementById("span2").innerHTML = "Please provide Age";
document.myForm.age.focus();
document.getElementById("age").style.border = "2px solid red";
return false;
}
else if (!ageFormat.test(age)) {
document.getElementById("span2").innerHTML = "Age can't be leass than 18 and greater than 60";
document.myForm.age.focus();
document.getElementById("age").style.border = "2px solid red";
return false;
}
else {
document.getElementById("span2").innerHTML = "";
document.getElementById("age").style.border = "2px solid green";
}
var password = document.myForm.password.value;
if (document.myForm.password.length < 6) {
alert("Error: Password must contain at least six characters!");
document.myForm.password.focus();
document.getElementById("password").style.border = "2px solid red";
return false;
}
re = /[0-9]/g;
if (!re.test(password)) {
alert("Error: password must contain at least one number (0-9)!");
document.myForm.password.focus();
document.getElementById("password").style.border = "2px solid red";
return false;
}
re = /[a-z]/g;
if (!re.test(password)) {
alert("Error: password must contain at least one lowercase letter (a-z)!");
document.myForm.password.focus();
document.getElementById("password").style.border = "2px solid red";
return false;
}
re = /[A-Z]/g;
if (!re.test(password)) {
alert("Error: password must contain at least one uppercase letter (A-Z)!");
document.myForm.password.focus();
document.getElementById("password").style.border = "2px solid red";
return false;
}
re = /[$&+,:;=?##|'<>.^*()%!-]/g;
if (!re.test(password)) {
alert("Error: password must contain at least one special character!");
document.myForm.password.focus();
document.getElementById("password").style.border = "2px solid red";
return false;
}
else {
document.getElementById("span3").innerHTML = "";
document.getElementById("password").style.border = "2px solid green";
}
if (document.getElementById("data") == null)
createTable();
else {
appendRow();
}
return true;
}
function createTable() {
var myTableDiv = document.getElementById("myTable"); //indiv
table = document.createElement("TABLE"); //TABLE??
table.setAttribute("id", "data");
table.border = '1';
myTableDiv.appendChild(table); //appendChild() insert it in the document (table --> myTableDiv)
debugger;
var header = table.createTHead();
var th0 = table.tHead.appendChild(document.createElement("th"));
th0.innerHTML = "Name";
var th1 = table.tHead.appendChild(document.createElement("th"));
th1.innerHTML = "Age";
appendRow();
}
function appendRow() {
var name = document.myForm.name.value;
var age = document.myForm.age.value;
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
row.insertCell(0).innerHTML = name;
row.insertCell(1).innerHTML = age;
clearForm();
}
function clearForm() {
debugger;
document.myForm.name.value = "";
document.myForm.password.value = "";
document.myForm.age.value = "";
}
function restrictCharacters(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (((charCode >= '65') && (charCode <= '90')) || ((charCode >= '97') && (charCode <= '122')) || (charCode == '32')) {
return true;
}
else {
return false;
}
}
</script>
<div>
<form name="myForm">
<table id="tableid">
<tr>
<th>Name</th>
<td>
<input type="text" name="name" placeholder="Name" id="name" onkeypress="return restrictCharacters(event);" /></td>
<td><span id="span1"></span></td>
</tr>
<tr>
<th>Age</th>
<td>
<input type="text" onkeypress="return event.charCode === 0 || /\d/.test(String.fromCharCode(event.charCode));" placeholder="Age"
name="age" id="age" /></td>
<td><span id="span2"></span></td>
</tr>
<tr>
<th>Password</th>
<td>
<input type="password" name="password" id="password" placeholder="Password" /></td>
<td><span id="span3"></span></td>
</tr>
<tr>
<td></td>
<td>
<input type="button" value="Submit" onclick="check();" /></td>
<td>
<input type="reset" name="Reset" /></td>
</tr>
</table>
</form>
<div id="myTable">
</div>
</div>
var html = "";
for (var i = 0; i < data.length; i++){
html +="<tr>"+
"<td>"+ (i+1) + "</td>"+
"<td>"+ data[i].name + "</td>"+
"<td>"+ data[i].number + "</td>"+
"<td>"+ data[i].city + "</td>"+
"<td>"+ data[i].hobby + "</td>"+
"<td>"+ data[i].birthdate + "</td>"+"<td><button data-arrayIndex='"+ i +"' onclick='editData(this)'>Edit</button><button data-arrayIndex='"+ i +"' onclick='deleteData()'>Delete</button></td>"+"</tr>";
}
$("#tableHtml").html(html);
You can create a dynamic table rows as below:
var tbl = document.createElement('table');
tbl.style.width = '100%';
for (var i = 0; i < files.length; i++) {
tr = document.createElement('tr');
var td1 = document.createElement('td');
var td2 = document.createElement('td');
var td3 = document.createElement('td');
::::: // As many <td> you want
td1.appendChild(document.createTextNode());
td2.appendChild(document.createTextNode());
td3.appendChild(document.createTextNode();
tr.appendChild(td1);
tr.appendChild(td2);
tr.appendChild(td3);
tbl.appendChild(tr);
}
when you say 'appendchild' you actually move your child from one parent to another.
you have to create a node for each cell.
In my example, serial number is managed according to the actions taken on each row using css. I used a form inside each row, and when new row created then the form will get reset.
/*auto increment/decrement the sr.no.*/
body {
counter-reset: section;
}
i.srno {
counter-reset: subsection;
}
i.srno:before {
counter-increment: section;
content: counter(section);
}
/****/
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type='text/javascript'>
$(document).ready(function () {
$('#POITable').on('change', 'select.search_type', function (e) {
var selectedval = $(this).val();
$(this).closest('td').next().html(selectedval);
});
});
</script>
<table id="POITable" border="1">
<tr>
<th>Sl No</th>
<th>Name</th>
<th>Your Name</th>
<th>Number</th>
<th>Input</th>
<th>Chars</th>
<th>Action</th>
</tr>
<tr>
<td><i class="srno"></i></td>
<td>
<select class="search_type" name="select_one">
<option value="">Select</option>
<option value="abc">abc</option>
<option value="def">def</option>
<option value="xyz">xyz</option>
</select>
</td>
<td></td>
<td>
<select name="select_two" >
<option value="">Select</option>
<option value="123">123</option>
<option value="456">456</option>
<option value="789">789</option>
</select>
</td>
<td><input type="text" size="8"/></td>
<td>
<select name="search_three[]" >
<option value="">Select</option>
<option value="one">1</option>
<option value="two">2</option>
<option value="three">3</option>
</select>
</td>
<td><button type="button" onclick="deleteRow(this)">-</button><button type="button" onclick="insRow()">+</button></td>
</tr>
</table>
<script type='text/javascript'>
function deleteRow(row)
{
var i = row.parentNode.parentNode.rowIndex;
document.getElementById('POITable').deleteRow(i);
}
function insRow()
{
var x = document.getElementById('POITable');
var new_row = x.rows[1].cloneNode(true);
var len = x.rows.length;
//new_row.cells[0].innerHTML = len; //auto increment the srno
var inp1 = new_row.cells[1].getElementsByTagName('select')[0];
inp1.id += len;
inp1.value = '';
new_row.cells[2].innerHTML = '';
new_row.cells[4].getElementsByTagName('input')[0].value = "";
x.appendChild(new_row);
}
</script>
Hope this helps.
In My example call add function from button click event and then get value from form control's and call function generateTable.
In generateTable Function check first Table is Generaed or not. If table is undefined then call generateHeader Funtion and Generate Header and then call addToRow function for adding new row in table.
<input type="button" class="custom-rounded-bttn bttn-save" value="Add" id="btnAdd" onclick="add()">
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div class="dataGridForItem">
</div>
</div>
</div>
//Call Function From Button click Event
var counts = 1;
function add(){
var Weightage = $('#Weightage').val();
var ItemName = $('#ItemName option:selected').text();
var ItemNamenum = $('#ItemName').val();
generateTable(Weightage,ItemName,ItemNamenum);
$('#Weightage').val('');
$('#ItemName').val(-1);
return true;
}
function generateTable(Weightage,ItemName,ItemNamenum){
var tableHtml = '';
if($("#rDataTable").html() == undefined){
tableHtml = generateHeader();
}else{
tableHtml = $("#rDataTable");
}
var temp = $("<div/>");
var row = addToRow(Weightage,ItemName,ItemNamenum);
$(temp).append($(row));
$("#dataGridForItem").html($(tableHtml).append($(temp).html()));
}
//Generate Header
function generateHeader(){
var html = "<table id='rDataTable' class='table table-striped'>";
html+="<tr class=''>";
html+="<td class='tb-heading ui-state-default'>"+'Sr.No'+"</td>";
html+="<td class='tb-heading ui-state-default'>"+'Item Name'+"</td>";
html+="<td class='tb-heading ui-state-default'>"+'Weightage'+"</td>";
html+="</tr></table>";
return html;
}
//Add New Row
function addToRow(Weightage,ItemName,ItemNamenum){
var html="<tr class='trObj'>";
html+="<td>"+counts+"</td>";
html+="<td>"+ItemName+"</td>";
html+="<td>"+Weightage+"</td>";
html+="</tr>";
counts++;
return html;
}
You can do that using LemonadeJS.
<html>
<script src="https://lemonadejs.net/v2/lemonade.js"></script>
<div id='root'></div>
<script>
var Component = (function() {
var self = {};
self.rows = [
{ title:'Google', description: 'The alpha search engine...' },
{ title:'Bind', description: 'The microsoft search engine...' },
{ title:'Duckduckgo', description: 'Privacy in the first place...' },
];
// Custom components such as List should always be unique inside a real tag.
var template = `<table cellpadding="6">
<thead><tr><th>Title</th><th>Description</th></th></thead>
<tbody #loop="self.rows">
<tr><td>{{self.title}}</td><td>{{self.description}}</td></tr>
</tbody>
</table>`;
return lemonade.element(template, self);
});
lemonade.render(Component, document.getElementById('root'));
</script>
</html>

Categories