I have an infinite select2 by using button to show select2 but it doesn't work, is there something wrong with my script?
this is the script to add unlimited select2 with onclick button :
<div id="cont"></div>
<button id="addRow" onclick="addRow();"> Add Rows</button>
This is a function to call select2
<script type="text/javascript">
var arrHead = new Array();
arrHead = ['AKUN', 'DEBIT', 'CREDIT','#'];
function createTable() {
var empTable = document.createElement('div');
empTable.setAttribute('class', 'ed-tab');
empTable.innerHTML = `
<table id="empTable" class="table table-borderedless table-striped w-100">
<thead>
<tr>
<th width="50%">AKUN</th>
<th width="22%">DEBIT</th>
<th width="22%">CREDIT</th>
<th width="6%" class="text-center">#</th>
<tr>
</thead>
<tbody>
<tr></tr>
<tr></tr>
</tbody>
</table>
`;
var div = document.getElementById('cont');
div.appendChild(empTable);
}
function addRow() {
var empTab = document.getElementById('empTable');
var rowCnt = empTab.rows.length;
var tr = empTab.insertRow(rowCnt);
for (var c = 0; c < arrHead.length; c++) {
var td = document.createElement('td');
td = tr.insertCell(c);
if (c == 0) {
var select = document.createElement("select");
select.setAttribute('type', 'text');
select.setAttribute('class', 'form-control select_ids');
select.innerHTML = `
<select class="form-control form-search" placeholder="tes" type="text" >
<option></option>
<?php
$kodeakun_q = $db->query("SELECT * FROM tb_akun WHERE parent_akun >= 0");
if ($kodeakun_q->num_rows > 0) {
while($row = $kodeakun_q->fetch_assoc()){
?>
<option id="func/f_insert.php?select_id=<?= $row['kode_akun'] ?>" value="<?= $row['kode_akun'] ?>">
<?= $row['kode_akun']; ?> | <?= $row['nama_akun'] ?>
</option>
<?php } } ?>
</select>
`;
td.appendChild(select);
}else if( c == 1){
var ele = document.createElement('input');
ele.setAttribute('type', 'text');
ele.setAttribute('class', 'form-control');
ele.setAttribute('value', '');
td.appendChild(ele);
}else if (c == 2) {
var ele = document.createElement('input');
ele.setAttribute('type', 'text');
ele.setAttribute('class', 'form-control');
ele.setAttribute('value', '');
td.appendChild(ele);
}else if(c == 3){
var button = document.createElement("button");
button.setAttribute('class', 'btn btn-danger');
button.setAttribute('onclick', 'removeRow(this)');
button.innerHTML = `<i class="fas fa-trash"></i>`;
td.appendChild(button);
}
}
}
function removeRow(oButton) {
var empTab = document.getElementById('empTable');
empTab.deleteRow(oButton.parentNode.parentNode.rowIndex);
}
function submit() {
var myTab = document.getElementById('empTable');
var arrValues = new Array();
for (row = 1; row < myTab.rows.length - 0; row++) {
for (c = 0; c < myTab.rows[row].cells.length; c++) {
var element = myTab.rows.item(row).cells[c];
if (element.childNodes[0].getAttribute('type') == 'text') {
arrValues.push("'" + element.childNodes[0].value + "'");
}
}
}
console.log(arrValues);
}
</script>
this is the main script for the select2 :
<script>
$(document).ready(function(){
$(".select_ids").selectize({
placeholder: "Pilih Akun . . .",
allowClear: true,
});
});
</script>
Note :
I have added a function in onclick button to call the select2, but it only works in the first select2 and when I add select2 it doesn't work properly.
you just need bind element select after added to table
for (var c = 0; c < arrHead.length; c++) {
.
..
...
}
// bind element
$('.select_ids').select2()
Demo jsfiddle : https://jsfiddle.net/4uja63fh/
Related
Please someone help me convert this jQuery function into a JavaScript onkeyup or onchange function. I'm always getting an error undefined when I try to alter it as a JavaScript.
Your help will be deeply appreciated.
var inp = $("#txt");
var tbl = document.getElementById("myTable");
// where #txt is the id of the textbox
inp.keyup(function (event) {
if (event.keyCode == 13) {
if (inp.val().length > 0) {
var trow = document.createElement('tr');
var tdata_type = document.createElement('td');
var tdata_code = document.createElement('td');
tdata_type.textContent = $("#select option:selected").text();
tdata_code.textContent = inp.val();
trow.appendChild(tdata_code);
trow.appendChild(tdata_type);
tbl.insertBefore(trow,tbl.firstChild);
}else{
alert("Barcode length insufficient");
}
inp.val('');
}
});
Tried this but I got errors. (index):86 Uncaught ReferenceError: barcode is not defined
at HTMLInputElement.onkeyup
<input type="text" name="yes" id="txt" onkeyup="barcode()">
function barcode(){
var inp = $("#txt");
var tbl = document.getElementById("myTable");
if (event.keyCode == 13) {
if (inp.val().length > 0) {
var trow = document.createElement('tr');
var tdata_type = document.createElement('td');
var tdata_code = document.createElement('td');
tdata_type.textContent = $("#select option:selected").text();
tdata_code.textContent = inp.val();
trow.appendChild(tdata_code);
trow.appendChild(tdata_type);
tbl.insertBefore(trow,tbl.firstChild);
}else{
alert("Barcode length insufficient");
}
inp.val('');
}
}
See here to full tried code: http://jsfiddle.net/sLzsweyd/
function barcode(event) {
var inp = $("#txt");
var tbl = document.getElementById("myTable");
if (event.keyCode == 13) {
if (inp.val().length > 0) {
var trow = document.createElement('tr');
var tdata_type = document.createElement('td');
var tdata_code = document.createElement('td');
tdata_type.textContent = $("#select option:selected").text();
tdata_code.textContent = inp.val();
trow.appendChild(tdata_code);
trow.appendChild(tdata_type);
tbl.insertBefore(trow, tbl.firstChild);
} else {
alert("Barcode length insufficient");
}
inp.val('');
}
}
.table-header {}
.table-cell {
width: 100px;
height: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<select id="select">
<option>Statement of Account</option>
<option>Disconnection Notice</option>
</select>
<input type="text" name="yes" id="txt" onkeyup="barcode(event)">
<table>
<thead>
<tr class="table-header">
<td class="table-cell">Type</td>
<td class="table-cell">Barcode</td>
</tr>
</thead>
<tbody id="myTable">
<tr class="table-row">
<td class="table-cell-text">
</td>
<td class="table-cell-text">
</td>
</tr>
</tbody>
</table>
You have set the LOAD TYPE as onLoad.
So jsfiddle has added a wrapper around your function.
$(window).load(function(){
function barcode() {
}
});
Change the LOAD TYPE to No wrap - in <head>
Updated fiddle
<input type="text" name="yes" onkeyup="barcode()" />
<script>
function barcode( event ) {
if ( event.keyCode == 13 ) {
if ( this.value.length > 0 ) {
var tbl = document.getElementById( 'myTable' ),
trow = document.createElement( 'tr' ),
tdata_type = document.createElement( 'td' ),
tdata_code = document.createElement( 'td' ),
select_el = document.getElementById( 'select' );
tdata_type.innerHTML = select_el.options[ select_el.selectedIndex ].value;
tdata_type.innerHTML = this.value;
trow.appendChild( tdata_code );
trow.appendChild( tdata_type );
tbl.insertBefore( trow, tbl.firstChild );
} else {
alert( 'Barcode length insufficient' );
}
this.value = '';
}
}
</script>
Script:-
<script type="text/javascript">
$(document).ready(function () {
$("#cbSelectAll").click(function () {
if (this.checked) {
$(':checkbox').each(function () {
this.checked = true;
var selectall = document.getElementsByClassName(".checkBoxClass");
var cid = $(this).attr('id');
console.log('cid' + cid);
var hidSelectAll = document.getElementById("hfSelectAll");
var hidCustomer = document.getElementById("hfCustomerID");
hidCustomer = '';
var str = 'Select All';
hidSelectAll.value = str;
console.log(hidSelectAll);
});
$("#GridRows .checkBoxClass").change(function () {
if (!$(this).prop("checked")) {
$("#cbSelectAll").prop("checked", false);
var cid = $(this).attr('id');
console.log('cid' + cid);
var hidSelectAll = document.getElementById("hfSelectAll");
var str = 'Select All + unselected values';
hidSelectAll.value = str;
console.log(hidSelectAll);
}
});
}
else {
$(':checkbox').each(function () {
this.checked = false;
var hidSelectAll = document.getElementById("hfSelectAll");
var str = 'UnSelect All';
hidSelectAll.value = str;
console.log(hidSelectAll);
});
$(".checkBoxClass").change(function () {
if (!$(this).prop("checked")) {
$("#cbSelectAll").prop("checked", false);
var hidSelectAll = document.getElementById("hfSelectAll");
var str = 'unSelect All + selected values';
hidSelectAll.value = str;
console.log(hidSelectAll);
}
});
}
});
});
</script>
HTML:-
<body>
<h4>Number Of Records - <span>#ViewBag.ItemCount</span> </h4>
<div class="table-responsive" style="padding-left:20%;">
<table class="table-fill" style="float:left;">
<thead>
<tr>
<th class="text-left">
Select All
<div class="checkbox">
<input style="margin-left:15px;" type="checkbox" id="cbSelectAll" />
</div>
</th>
<th class="text-left" style="padding-left:27px;">
First Name
</th>
<th class="text-left" style="padding-left:32px;">
Last Name
</th>
<th class="text-left" style="padding-left:40px;padding-right: 60px;">
Email-ID
</th>
<th class="text-left" style="padding-left:30px;padding-right: 40px;">
Customer Type
</th>
<th class="text-left" style="padding-left:15px;">
Customer Designation
</th>
</tr>
</thead>
</table>
<div id="GridRows" style="width:65%;">
</div>
</div>
<div id="pager"></div>
<input type="hidden" id="currentPage">
<input type="hidden" id="hfCustomerID"/>
<input type="hidden" id="hfSelectAll" />
</body>
this is html. Rows generated dynamically from jquery ajax call to avoid loss of values stored in hidden field on page load.
In this when clicked on select all checked box all values of table
from same page selected.
how to store all values of table from multiple pagination when clicked
on Select All checkbox?
what are option for storing all values of table?
Actually your checkAll(..) is hanging without any attachment.
1) Add onchange event handler
2) Modified the code to handle check/uncheck
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var element1 = document.createElement("input");
element1.type = "checkbox";
element1.name = "chkbox[]";
cell1.appendChild(element1);
var cell2 = row.insertCell(1);
cell2.innerHTML = rowCount;
var cell3 = row.insertCell(2);
cell3.innerHTML = rowCount;
var cell4 = row.insertCell(3);
cell4.innerHTML = rowCount;
var cell5 = row.insertCell(4);
cell5.innerHTML = rowCount;
var cell6 = row.insertCell(5);
cell6.innerHTML = rowCount;
}
function deleteRow(tableID) {
try {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for (var i = 1; i < rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if (null != chkbox && true == chkbox.checked) {
table.deleteRow(i);
rowCount--;
i--;
}
}
} catch (e) {
alert(e);
}
}
function checkAll(ele) {
var checkboxes = document.getElementsByTagName('input');
if (ele.checked) {
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].type == 'checkbox') {
checkboxes[i].checked = true;
}
}
} else {
for (var i = 0; i < checkboxes.length; i++) {
console.log(i)
if (checkboxes[i].type == 'checkbox') {
checkboxes[i].checked = false;
}
}
}
}
<INPUT type="button" value="Add Row" onclick="addRow('dataTable')" />
<INPUT type="button" value="Delete Row" onclick="deleteRow('dataTable')" />
<TABLE id="dataTable" border="1">
<tr>
<th>
<INPUT type="checkbox" onchange="checkAll(this)" name="chk[]" />
</th>
<th>Make</th>
<th>Model</th>
<th>Description</th>
<th>Start Year</th>
<th>End Year</th>
</tr>
</TABLE>
You can if you are using datatable.
$(document).ready(function () {
var oTable = $('#example').dataTable({
stateSave: true
});
var allPages = oTable.fnGetNodes();
$('body').on('click', '#selectAll', function () {
if ($(this).hasClass('allChecked')) {
$('input[type="checkbox"]', allPages).prop('checked', false);
} else {
$('input[type="checkbox"]', allPages).prop('checked', true);
}
$(this).toggleClass('allChecked');
})
});
There is one more option i.e. you have to add same class name on all checkboxes and add this code.(If you not use datatable).
var select_all = document.getElementById("select_all");
var checkboxes = document.getElementsByClassName("checkbox");
select_all.addEventListener("change", function(e){
for (i = 0; i < checkboxes.length; i++) {
checkboxes[i].checked = select_all.checked;
}
});
for(var i = 0; i < checkboxes.length; i++) {
checkboxes[i].addEventListener('change', function(e){ //".checkbox" change
//uncheck "select all", if one of the listed checkbox item isunchecked
if(this.checked == false){
select_all.checked = false;
}
if(document.querySelectorAll('.checkbox:checked').length ==checkboxes.length){
select_all.checked = true;
}
});
}
First off, I'm sorry for my poor English.
I'm making information system for school and have a problem when I update data for student. There are siblings fields on student form. They can add one or more siblings (one to many relationship). The program has been successfully to adding siblings into databases (there are two databases, student (id [auto increment - primary key], student_id name, sex, age, ..., etc) and siblings (id (primary key), student_id, siblings_name, siblings_age, ..., etc).
But, the program has been failed when I update siblings data.
ADD SIBLINGS
php:
<table id='siblingsTable'>
<a href='javascript:void(0);' onclick='addRow()'><img src='../images/add.png'/></a>
<a href='javascript:void(0);' onclick='deleteRow()'><img src='../images/delete.png'/></a><br />
<th>Name</th>
<th>Age</th>
<th></th>
</table>
js:
<script>
function addRow() {
var table = document.getElementById("siblingsTable");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var element1 = document.createElement("input");
element1.type = "text";
element1.name = "siblings_name[]";
element1.value = "";
cell1.appendChild(element1);
var cell2 = row.insertCell(1);
var element2 = document.createElement("input");
element2.type = "text";
element2.name = "siblings_age[]";
element2.value = "";
cell2.appendChild(element2);
}
function deleteRow() {
var table = document.getElementById("siblingsTable");
var rowCount = table.rows.length;
table.deleteRow(rowCount -1);
}
</script>
saving to database:
if (!empty($_POST['siblings_name']) && !empty($_POST['siblings_age']) && is_array($_POST['siblings_name']) && is_array($_POST['siblings_age']) && count($_POST['siblings_name']) === count($_POST['siblings_age'])) {
$auth_array = $_POST['auth_key'];
$name_array = $_POST['siblings_name'];
$age_array = $_POST['siblings_age'];
for ($i = 0; $i < count($name_array); $i++) {
$auth = mysql_real_escape_string($auth_array);
$name = mysql_real_escape_string($name_array[$i]);
$age = mysql_real_escape_string($age_array[$i]);
mysql_query("INSERT INTO skkk_web_siblings (auth_key, siblings_name, siblings_age) VALUES ('$auth', '$name', '$age')");
}
}
This is my problem when i want to updating data:
$sib = mysql_query("SELECT COUNT(auth_key) FROM skkk_web_siblings WHERE auth_key = '$_GET[id]'");
$totalsiblings = mysql_result($sib,0);
...
$siblings = mysql_query("SELECT * FROM skkk_web_siblings WHERE auth_key = '$_GET[id]'");
while($row = mysql_fetch_array($siblings)){
$id = $row['id'];
$name = $row['siblings_name'];
$age = $row['siblings_age'];
$siblingsname[] = $name;
$siblingsage[] = $age;
}
...
...
...
<table id='siblingsTable'>
<a href='javascript:void(0);' onclick='editRow()'><img src='../images/edit.png'/></a><br />
<th>Name</th>
<th>Age</th>
</table>
...
<script>
function editRow() {
var table = document.getElementById("siblingsTable");
var total = '<?php echo $totalsiblings; ?>';
var name = jQuery.parseJSON('<?php echo json_encode($siblingsname); ?>');
var age = jQuery.parseJSON('<?php echo json_encode($siblingsage); ?>');
var i;
var table = '';
for (i = 0; i < total; i++) {
tbl += '<input type="text" name="siblings_name[]" value="' + name[i] + '"/>';
tbl += '<input type="text" name="siblings_age[]" value="' + age[i] + '"/>';
}
document.getElementById("siblingsTable").innerHTML = table;
}
</script>
...
//updating to database
if (!empty($_POST['siblings_name']) && !empty($_POST['siblings_age']) && is_array($_POST['siblings_name']) && is_array($_POST['siblings_age']) && count($_POST['siblings_name']) === count($_POST['siblings_age'])) {
$name_array = $_POST['siblings_name'];
$age_array = $_POST['siblings_age'];
for ($i = 0; $i < count($name_array); $i++) {
$name = mysql_real_escape_string($name_array[$i]);
$age = mysql_real_escape_string($age_array[$i]);
mysql_query("UPDATE skkk_web_siblings SET siblings_name = '$name', siblings_age = '$age' WHERE auth_key = '$_POST[id]'");
}
}
When I update one name, it changes all siblings name. What should I do?
Thanks for your help.
I'm trying to add and remove the row and column from a table dynamically. While I'm trying this with static contents my code working fine. Same thing I'm trying with fetching data from database and adding deleting row/column it's not working.. added rows are getting deleted but the value contains from mysql row and column not getting deleted.
JavaScript:
//*********************************Start Add Row **********************************************************
function addRowToTable() {
var tbl = document.getElementById('tbl_sales');
var columnCount = tbl.rows[0].cells.length;
var rowCount = tbl.rows.length;
var row = tbl.insertRow(rowCount);
// For Every Row Added a Checkbox on first cell--------------------------------------
var cell_1 = row.insertCell(0);
var element_1 = document.createElement("input");
element_1.type = "checkbox";
element_1.setAttribute('id', 'newCheckbox');
cell_1.appendChild(element_1);
// For Every Row Added add a Select box on Second cell------------------------------
var cell_2 = row.insertCell(1);
var element_2 = document.createElement('input');
element_2.type = "text";
element_2.setAttribute('id', 'rows');
element_2.setAttribute('name', 'rows[]');
cell_2.appendChild(element_2);
// For Every Row Added add a textbox on the rest of the cells starting with the 3rd,4th,5th... coloumns going on...
if (columnCount >= 2) {
for (var i = 3; i <= columnCount; i++) {
var newCel = row.insertCell(i - 1);
var element_3 = document.createElement("input");
element_3.type = "text";
element_3.setAttribute('id', 'name');
element_3.setAttribute('name', 'name[]');
newCel.appendChild(element_3);
}
}
}
//***************************** End Add Row ***************************************************************
// *****************************Start Add Column**********************************************************
function addColumn() {
var tblBodyObj = document.getElementById('tbl_sales').tBodies[0];
var rowCount = tblBodyObj.rows.length;
//for every Coloumn Added Add checkbox on first row ----------------------------------------------
var newchkbxcell = tblBodyObj.rows[0].insertCell(-1);
var element_4 = document.createElement("input");
element_4.type = "checkbox";
element_4.setAttribute('id', 'newCheckbox');
newchkbxcell.appendChild(element_4);
//For Every Coloumn Added add Drop down list on second row-------------------------------------
var newselectboxcell = tblBodyObj.rows[1].insertCell(-1);
var element_5 = document.createElement('input');
element_5.type = "text";
element_5.setAttribute('id', 'cols');
element_5.setAttribute('name', 'cols[]');
newchkbxcell.appendChild(element_4);
newselectboxcell.appendChild(element_5);
for (var i = 2; i < tblBodyObj.rows.length; i++) {
var newCell = tblBodyObj.rows[i].insertCell(-1);
var element_6 = document.createElement("input");
element_6.type = "text"
element_6.setAttribute('id', 'name');
element_6.setAttribute('name', 'name[]');
newCell.appendChild(element_6)
}
}
//*****************************Start Delete Selected Rows **************************************************
function deleteSelectedRows() {
var tb = document.getElementById('tbl_sales');
var NoOfrows = tb.rows.length;
for (var i = 0; i < NoOfrows; i++) {
var row = tb.rows[i];
var chkbox = row.cells[0].childNodes[0];
if (null != chkbox && true == chkbox.checked) {
tb.deleteRow(i);
NoOfrows--;
i--;
}
}
}
//*****************************End Delete Selected Columns **************************************************
//*****************************Start Delete Selected Columns ************************************************
function deleteSelectedColoumns() {
var tb = document.getElementById('tbl_sales');
var NoOfcolumns = tb.rows[0].cells.length;
for (var clm = 3; clm < NoOfcolumns; clm++) {
var rw = tb.rows[0];
var chkbox = rw.cells[clm].childNodes[0];
console.log(clm, NoOfcolumns, chkbox);
if (null != chkbox && true == chkbox.checked) {
//-----------------------------------------------------
var lastrow = tb.rows;
for (var x = 0; x < lastrow.length; x++) {
tb.rows[x].deleteCell(clm);
}
//-----------------------------------------
NoOfcolumns--;
clm--;
} else {
//alert("not selected");
}
}
}
function deleteAllRows() {
var tbl = document.getElementById('tbl_sales'); // table reference
lastRow = tbl.rows.length - 1; // set the last row index
// delete rows with index greater then 0
for (i = lastRow; i > 0; i--) {
tbl.deleteRow(i); //delete the row
}
}
//*****************************End Delete Selected Columns **************************************************
//window.onload = function () {addColumn();addColumn();addColumn();};
Page:
<table width="30" border="1" id="tbl_sales">
<tr>
<td></td>
<td><strong>Columns</strong> </td>
{php}
$j = 0;
for($i=0;$i<count($rows[0]);$i++)
{
{/php}
<td>
{php} if($j == 0) { {/php}
<input type="button" name="adclmbutton" id="addclmnbutton" value="Add Columns" onclick="addColumn()" />
{php}}else{{/php}
<input type="checkbox" id="newCheckbox">
{php}}{/php}
</td>
{php}$j++;}{/php}
</tr>
<tr>
<td><strong>Rows</strong> </td>
<td><strong>Rows Grid</strong> </td>
{php}
$j = 0;
for($i=0;$i<count($rows[0]);$i++)
{
{/php}
<td><input type="text" name="cols[]" value="{php} echo $rows[0][$i]; {/php}" id=""/></td>
{php}}$i++;{/php}
</tr>
{php}
$seats = $CI->model_theatre->convetTable($m_arr);
unset($seats[0]);
$i = 0;
foreach ($seats as $rowName => $columns)
{
{/php}
<tr >
<td>
{php} if($i == 0) { {/php}
<input type="button" name="addrowbutton" id="adrwbutton" value="Add Row" onclick="addRowToTable();"/>
{php}}else{{/php}
<input type="checkbox" id="newCheckbox">
{php}}{/php}</td>
<td><input type="text" name="rows[]" value="{php}echo $rowName;{/php}" /></td>
{php}
foreach ($columns as $cell)
{
{/php}
<td><label for="textfield"></label><input type="text" name="name[]" value="{php} echo $cell;{/php}" width="50px" /></td>
{php}
}
{/php}
</tr>
{php}
$i++;
}
{/php}
</table>
{php}
}
{/php}
<p>
<input type="button" name="button3" id="button3" value="Remove Selected Row" onClick="deleteSelectedRows()" />
<input type="button" value="Delete all rows" onClick="deleteAllRows()" />
<input type="button" name="button4" id="button4" value="Remove Selected Column" onClick="deleteSelectedColoumns()" />
</p>
When you are adding, deleting row you also need to add, delete that row in database by using AJAX call.
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>