Create div within a cell in Javascript - javascript

I am having troubles creating a div after creating a cell dynamically using Javascript. My goal is to be able to add the exact same original table row and its contents below. Below is the HTML code:
<table width="100%" id="processTable">
<tr>
<td id="ProcessDetails"><div id="description">Replace with description.</div>
<div id="QuestionToAnswer"><b>Replace with a question answerable by YES or NO</b></div>
</td>
<td id="AvailableAnswersColumn">
<p id="option1">YES</p>
<p id="option2">NO: Proceed to next question</p>
</td>
</tr>
<!--Insert new table row if needed-->
</table>
<div id="footer">
<input type="button" value="Insert Table Row" id="CreateRow" class="CreateRow" onclick="insertRow()" />
</div>
Here is the Javascript
<script>
function insertRow() {
var table = document.getElementById("processTable");
var row = table.insertRow(1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = //within this cell should be created the div ids "description" + "QuestionToAnswer";
cell2.innerHTML = //within this cell should be created the paragraph with ids "option1" + "option2";;
cell1.setAttribute("id", "ProcessDetails", 0);
cell2.setAttribute("id", "AvailableAnswersColumn", 1);
}
</script>
Please help.

document.createElement will be your friend here.
var div = document.createElement("div");
div.innerHTML = "Replace with description.";
cell1.appendChild(div);
With document.createElement(<tagname>) you can create any html element you want with JavaScript code. You can append it to the cell by using appendChild. Since div in my example is an object and a reference to a DOM node after it gets appended you can set event handlers to it etc.

Related

Creating a timetable using JavaScript

I am trying to create a web page where user can create his own schedule. User can enter the values of lines and columns in some input to build a table in which the user will write his schedule. I use this javascript code:
var p = document.getElementById('paragraph');
var table = document.createElement('table');
var tbody = document.createElement('tbody');
table.appendChild(tbody);
for (let i = 0; i < lines; i++){
let tr = document.createElement('tr');
for (let j = 0; j < columns; j++){
let td = document.createElement('td');
}
tbody.appendChild(tr);
}
p.appendChild(table);
However, when I'am trying to add information to table cells, I can't write values to each of them. I've used .innerHTML but it doesn't work the way it needs to. The information will be written only to the beginning of the table.
Should I give id to each td and then address to them by id when I need to write the information? Or there is another way to write values to table cells?
I think you need something like this to insert the data.
We have insertRow(), which is pre-defined function which i used in this answer to insert new row and then inserted columns in it with insertCell function.
<!DOCTYPE html>
<html>
<body>
<div class="inputs">
<input type="text" id="input1" placeholder="Enter first col data" >
<input type="text" id="input2" placeholder="Enter second col data" >
</div>
<br> <br> <br>
<table id="myTable">
<thead style="background-color: beige;">
<tr>
<td>default head row cell 1</td>
<td>default head row cell 2</td>
</tr>
</thead>
<tbody></tbody>
</table>
<br>
<button type="button" onclick="myFunction()">add data to body row</button>
<script>
function myFunction() {
var table = document.querySelector("#myTable tbody");
var row = table.insertRow();
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
const val1 = document.getElementById('input1').value;
const val2 = document.getElementById('input2').value;
cell1.innerHTML = val1;
cell2.innerHTML = val2;
}
</script>
</body>
</html>
I think that you need to refer to your button in the js file and write a function that will be executed on the "onclick" event
In this function, you are accessing the table variable. By using the built in javaScript function «insertRow()» you are adding rows to your table. Then you should add cells to this row in which information that users entered will be stored. This you can also do by using build in function «insertCell()»
Next, you access the fields in which the user has entered data
Retrieve values ​​using the «value» built-in function
Using the built-in «innerHTML» function, draw cells with the information that you received in the previous step
You can look at the written code below for better assimilation of information
<!DOCTYPE html>
<html>
<body>
<div class="inputs" >
<input type="text" id="firstColumn" placeholder="Enter data here" >
<input type="text" id="SecondColumn" placeholder="Enter data here" >
</div>
<table id="Table">
<thead>
<tr>
<td style="background-color: pink;">Name of first column</td>
<hr>
<td style="background-color: purple;">Name of second column</td>
</tr>
</thead>
<tbody></tbody>
</table>
<br>
<button style="background-color: yellow;" type="button" id = "btn">Add</button>
<script>
const button = document.querySelector('#btn');
btn.onclick = function() {
var table = document.querySelector("#Table tbody");
var row = table.insertRow();
var Fcell = row.insertCell(0);
var Scell = row.insertCell(1);
const Fdata = document.getElementById('firstColumn').value;
const Sdata = document.getElementById('SecondColumn').value;
Fcell.innerHTML = Fdata;
Scell.innerHTML = Sdata;
}
</script>
</body>
</html>

How to set html properties of a newly added cell through javascript

<script>
function myFunction() {
var table = document.getElementById("traTable");
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell2.innerHTML = "<td><input type="/text/"size="/30/"/></td>";
</script>
I have the following code and what I am trying to do is, when the user clicks on the button which fires this script. I want to add a new cell to the table. However, i need the cell which is added to be an input text box type. Is innerHTML is the right thing to use here?
You do not need to specify the <td> tag in cell2.innerHTML, simply do:
cell2.innerHTML = "<input type='text' size='30'/>"
function myFunction() {
var table = document.getElementById("traTable");
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell2.innerHTML = "<input type='text' size='30'/>";
}
<table id="traTable" border='1'>
<tr>
<td>First cell</td>
<td>Second cell</td>
<td>Third cell</td>
</tr>
</table><br>
<button onclick="myFunction()">Try it</button>
What you're doing there is adding a td (containing a textbox) to a td.
So the result of your code (assuming an otherwise empty table) will be:
<table id="traTable">
<tr>
<td></td>
<td>
<td>
<input type="text" size="30"/>
</td>
</td>
</tr>
</table>
which is clearly invalid due to the nested <td>s.
There is nothing ostensibly wrong with using innerHTML, but you have to set the value correctly. innerHTML overwrites what's inside the element, not the element itself.
cell2.innerHTML = '<input type="text" size="30"/>';
will get you the result you want (N.B. I also simplified your code to be more readable).
Demo:
function myFunction() {
var table = document.getElementById("traTable");
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell2.innerHTML = '<input type="text" size="30"/></td>';
}
myFunction();
console.log(document.getElementById("traTable").outerHTML);
table td { border: 1px solid blue; padding:5px; }
<table id="traTable">
</table>

Dynamically adding rows to a table

I'm trying to dynamically add a <tr> with two <td>s into a <table> via javascript, but my fiddle doesn't seem to do anything, does anyone see the problem?
Fiddle: https://jsfiddle.net/otL69Lpo/2/
HTML:
<button type="button" onclick="myFunction()">Click Me!</button>
<table class="table table-bordered" id="chatHistoryTable">
<tr>
<td>
12:30:30
</td>
<td>
text here
</td>
</table>
JS:
function myFunction() {
var table = document.getElementById("chatHistoryTable");
var tr = document.createElement("tr");
var td = document.createElement("td");
var td2 = document.createElement("td");
var txt = document.createTextNode("TIMESTAMP");
var txt2 = document.createTextNode("user: text");
td.appendChild(txt);
td2.appendChild(txt2);
tr.appendChild(td);
tr.appendChild(td2);
table.appendChild(tr);
}
Output should be as:
| TIMESTAMP | user: text |
This is a common issue in jsFiddle. There are several options for how to load the JS and you'll need to change the loading to either:
No wrap - in <head>
No wrap - in <body>

How to add to arraylist in javascript

I am using javascript for my server side validation.I need to add all data from a table which is dynamically generated while clicking an add button.
Clicking ADD button section is working fine.Also i added date picker to 2nd and 3rd columns.its working fine.The code is given below.....
function addRow(tableId) { //Add new row to given table having id tableId
var table = document.getElementById(tableId);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
cell1.innerHTML = '<input type="text" id="code'+ rowCount +'" name="code" maxlength="16"/>';
cell2.innerHTML = '<input type="text" id="datepicker2'+ rowCount +'" class="datepicker" name="validFrom" maxlength="50" >';
$('.datepicker').datepicker({
format: 'yyyy-mm-dd'
});
cell3.innerHTML = '<input type="text" id="datepicker3'+ rowCount +'" class="datepicker" name="validFrom" maxlength="50" >';
$('.datepicker').datepicker({
format: 'yyyy-mm-dd'
});
cell4.innerHTML = '<input type="button" id="del'+ rowCount +'" name="del" />';
Html code
<div class="systemsettings">
<h3><spring:message code="systemSetting.ratePeriods.label"/></h3>
</div>
<div class="systemset" >
<!-- table table-hover table-striped table-bordered table-highlight-head-->
<table id="systemsettingstid" class="table-bordered table-striped">
<thead class="tax_thead" id="tdDetailList">
<tr >
<!-- <th>Applicable From</th> -->
<th width="200" id="code" title="Code" >Code</th>
<th width="200" id="from" title="from ">from</th>
<th width="200" id="to" title="to">to</th>
<th width="50" id="del" title="del">del</th>
<!-- <th width="45" ><div class="add_new">
</div></th> -->
</tr>
</thead>
<tbody></tbody>
</table>
</div>
<div>
<tr>
<button type="button" onClick="javascript:addRow('systemsettingstid');">Add</button>
</tr>
</div>
DELETE BUTTON:
I have a delete button also appended inside the html code.
While clicking it the corresponding row should be deleted(fixed automatically while clicking add button on every row).
MY PROBLEM:
Adding and delete does not affect back end it just need to alter in an arraylist.
During final form submission the arraylist needs to go to backend(built in spring mvc).
1) Can we create an arraylist in javascript?
2) If we can how to add the text boxes and date picker details into arraylist?.
4) How to pass that arraylist in to my spring mvc controller?
NB:I am new to javascript.Any help will be highly appreciable.
<script>
var tdDetailList = [];
function init() {
var tdDetailTable = document.getElementById("tdDetailTable");
for (var i = 0, row; row = tdDetailTable.rows[i]; i++) {
var tdDetail = {code : row.cells[0].innerHTML, datepicker2 : row.cells[1].innerHTML, datepicker3 : row.cells[2].innerHTML};
tdDetailList.push(tdDetail);
}
alert(getDetailTableJson());
}
function deleteRow(index){
tdDetailList.splice(index, 1);
var tdDetailTable = document.getElementById("tdDetailTable");
tdDetailTable.deleteRow(index);
alert(getDetailTableJson());
}
function getDetailTableJson(){
return JSON.stringify(tdDetailList);
}
</script>
<body onload="init();">
<table id="tdDetailTable">
<tr><td>1</td><td>2</td><td>3</td><td>del</td></tr>
<tr><td>4</td><td>5</td><td>6</td><td>del</td></tr>
</table>
</body>
Can we create an arraylist in javascript?
Yes. In my example var tdDetailList = []; is array (list).
You can add elements to it:
tdDetailList.push(tdDetail);
and remove element in index: tdDetailList.splice(index, 1);
If we can how to add the text boxes and date picker details into arraylist?.
You can create object like:
var tdDetail = {code : row.cells[0].innerHTML, datepicker2 : row.cells[1].innerHTML, datepicker3 : row.cells[2].innerHTML};
with fields of your table and add the object to your list.
How to pass that arraylist in to my spring mvc controller?
Convert the list to json
JSON.stringify(tdDetailList);
In my example: "[{"code":"1","datepicker2":"2","datepicker3":"3"},{"code":"4","datepicker2":"5","datepicker3":"6"}]"
and send.
If you want to add and delete using JAVA SCRIPT then it will very complex and lengthy.
But using JQUERY it will work fine and easily you can handle ADD, DELETE actions also
use JQUERY and in this append and remove methods are there you can use it and insert a row in table and delete a row in table
May be you new in jQUERY but once you get it, its amazing than JAVA SCRIPT
Hope you getting let me know if you have any confusion. ['}

Dynamically insert table values based upon input?

Based upon user-input I want to generate a matrix / table for display. Here is the html
html
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252"/>
<title>lostBondUserPmtEntry</title>
<body>
<form name="test" ><font face="Verdana" size = "2">
<input name="Text1" type="text" /> score <br>
<input type="submit" Name ="test" id="gp"/>
<input type="hidden" name="dateFactor">
<table border="1">
<tr>
<td>sensitivity level</td>
<td>criticality level</td>
<td>priority level</td>
<td>Response time</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>high</td>
<td>2 hours</td>
</tr>
</table>
</form>
</body>
DEMO
The brief algo is
if score is 10 (certain value) populate the table as with predefined values (those values with column names are shown in DEMO). I want the table to be generated on particular button. I can call function, but I want to know how to append the html code for table on function call.
Thanks.
To append a row to the table you can try something like this:
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
cell1.innerHTML = "cell 1 text";
var cell2 = row.insertCell(1);
cell2.innerHTML = "cell 2 text";
var cell3 = row.insertCell(2);
cell3.innerHTML = "cell 3 text";
}

Categories

Resources