jQuery to JavaScript function - javascript

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>

Related

Javascript : 'select' and 'onclick' behavior isn't as expected

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/

How to make the script work in a program with html and java?

The script doesn't seem to be working when I'm running my code on sublime.On the contrary, when I run it in fiddle it does work. Here is the https://jsfiddle.net/m5wbdtLg/ . I can't append the question and dropdown in sublime while it is working fine on fiddle. I'm new to this, please help me out. Thank you.
I have tried including resources like this [How to make javascript function active in html
I have also tried $(document).ready(function(){..}); & <script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
$( "#add" ).click(function()
{var newElement = '<div class="container"><form id ="ques"><label>Question:</label><br><textarea rows="5" cols="50" name="description" placeholder="Enter a question"></textarea><br><select name="choice" id="choice" onchange="selectorchecker(this)"><option value="">Select choices</option><option value="checkbox">Checkbox</option><option value="radiobtn">Radio Button</option></select></form>';
$( "#ques" ).append( $(newElement) );
});
function selectorchecker(sel) {
document.getElementById("chkbox_choice").style.display = "none";
document.getElementById("rdbtn_choice").style.display = "none";if (sel.value) {
var show = sel.value=="checkbox"?"chkbox_choice":"rdbtn_choice";
document.getElementById(show).style.display = "block";
}
}
function addRowchk(tableID) {
var table_chk = document.getElementById(tableID);
var rowCount_chk = table_chk.rows.length;
var row_chk = table_chk.insertRow(rowCount_chk);
var cell1_chk = row_chk.insertCell(0);
var element1_chk = document.createElement("input");
element1_chk.type = "checkbox";
element1_chk.name="chkbox[]";
cell1_chk.appendChild(element1_chk);
var cell2_chk= row_chk.insertCell(1);
var element2_chk = document.createElement("input");
element2_chk.type = "text";
element2_chk.name = "txtbox[]";
cell2_chk.appendChild(element2_chk);
}
function deleteRowchk(tableID) {
try {
var table_chk = document.getElementById(tableID);
var rowCount_chk = table_chk.rows.length;
for(var i=0; i<rowCount_chk; i++) {
var row_chk = table_chk.rows[i];
var chkbox = row_chk.cells[0].childNodes[0];
if(null != chkbox && true == chkbox.checked) {
table_chk.deleteRow(i);
rowCount_chk--;
i--;
}
}
}catch(e) {
alert(e);
}
}
function addRowRd(tableID) {
var table_rd = document.getElementById(tableID);
var rowCount_rd = table_rd.rows.length;
var row_rd = table_rd.insertRow(rowCount_rd);
var cell1_rd = row_rd.insertCell(0);
var element1_rd = document.createElement("input");
element1_rd.type = "radio";
element1_rd.name="rdbtn[]";
cell1_rd.appendChild(element1_rd);
var cell2_rd= row_rd.insertCell(1);
var element2_rd= document.createElement("input");
element2_rd.type = "text";
element2_rd.name = "txtbox[]";
cell2_rd.appendChild(element2_rd);
}
function deleteRowRd(tableID) {
try {
var table_rd = document.getElementById(tableID);
var rowCount_rd = table_rd.rows.length;
for(var i=0; i<rowCount_rd; i++) {
var row_rd = table_rd.rows[i];
var rdbtn = row_rd.cells[0].childNodes[0];
if(null != rdbtn && true == rdbtn.checked) {
table_rd.deleteRow(i);
rowCount_rd--;
i--;
}
}
}catch(e) {
alert(e);
}
}
You randomly use jquery when everything else is vanilla js, why not just use all vanilla js?
document.getElementById("add").addEventListener("click",function(){
document.getElementById("ques").innerHTML += '<div class="container"><form id ="ques"><label>Question:</label><br><textarea rows="5" cols="50" name="description" placeholder="Enter a question"></textarea><br><select name="choice" id="choice" onchange="selectorchecker(this)"><option value="">Select choices</option><option value="checkbox">Checkbox</option><option value="radiobtn">Radio Button</option></select></form>';
});
<button type="button" id="add">ADD</button>
<div id="ques"></div>

Datatable not working properly

So I am generating a table with results which are returned from a JSON that is searched through and I would like to table to have pagionation, search, sorting options so I decided to use Data Tables. The table is being generated and populated with the correct results but the sorting options, the search and the pagination options do not appear at all. What am I doing wrong?
<!DOCTYPE html>
<html lang="en">
<head>
<title>Конкуренција</title>
</head>
<body>
<div id="cars" class="cars-container"></div>
<label for="amount">Цена:</label>
<input type="text" class="price-range-slider" id="amount" onclick="myFunction()" readonly style="border:0; color:#f6932f; font-weight:bold">
<div id="slider-range" style="width:300px"></div>
<br>
<p>
<label for="sili">Коњски сили:</label>
<input type="text" id="sili" onclick="myFunction()" readonly style="border:0; color:#f6931f; font-weight:bold;">
<div id="rejndz" style="width:300px" ></div>
<div>
<h4><label>Бренд</label></h4>
<select id="brand" multiple="multiple" onclick="myFunction()" data- style="btn-primary">
</select>
</div>
<br>
<div>
<h4><label>Тип на мотор</label></h4>
<select id="engineCap" multiple="multiple" onclick="myFunction()" >
</select>
<button onclick="myFunction(); dataTable(); ">Барај</button>
</table>
var selected = [];
var kapacitet = [];
var cena = [];
var hp = [];
var niza = [];
var finalKola = [];
function addTable() {
document.getElementById("results").innerHTML = "";
var myTableDiv = document.getElementById("results")
var tableBody = document.createElement('TBODY')
myTableDiv.border = '1'
myTableDiv.appendChild(tableBody);
var heading = [];
heading[0] = "Бренд"
heading[1] = "Модел"
heading[2] = "Капацитет"
heading[3] = "Коњски сили"
heading[4] = "Цена"
//koloni
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for (a = 0; a < heading.length; a++) {
var th = document.createElement('TH')
th.width = '75';
th.appendChild(document.createTextNode(heading[a]));
tr.appendChild(th);
}
//table rows
for (a = 0; a < finalKola.length; a++) {
var tr = document.createElement('TR');
var td = document.createElement('TD')
td.appendChild(document.createTextNode(finalKola[a].Brand));
tr.appendChild(td);
var td = document.createElement('TD')
td.appendChild(document.createTextNode(finalKola[a].Model));
tr.appendChild(td);
var td = document.createElement('TD')
td.appendChild(document.createTextNode(finalKola[a].engineCap));
tr.appendChild(td);
var td = document.createElement('TD')
td.appendChild(document.createTextNode(finalKola[a].sili));
tr.appendChild(td);
var td = document.createElement('TD')
td.appendChild(document.createTextNode(finalKola[a].amount + " €"));
tr.appendChild(td);
tableBody.appendChild(tr);
}
$(document).ready(function (){
{
$('#results').dataTable();
}
});
}
These are the errors I get in console:
Uncaught TypeError: Cannot read property 'mData' of undefined
at HTMLTableCellElement.<anonymous> (jquery.dataTables.min.js:88)
at Function.each (jquery.js:368)
at HTMLTableElement.<anonymous> (jquery.dataTables.min.js:88)
at Function.each (jquery.js:368)
at jQuery.fn.init.each (jquery.js:157)
at jQuery.fn.init.p [as dataTable] (jquery.dataTables.min.js:80)
at dataTable (index.html:268)
at HTMLButtonElement.onclick (index.html:75)
Assigning value to finalKola in the following code. This code takes values from two range slider and two buttons and searches through a JSON.
for(var u=0;u<koli.length;u++)
{
if((koli[u].sili > minSili) && (koli[u].sili < maxSili) && (parseInt(koli[u].amount.replace(',','')) > minCena) && (parseInt(koli[u].amount.replace(',','')) < maxCena))
{
if( (kapacitet.length > 0 && $.inArray(koli[u].engineCap,kapacitet) != -1) &&
(selected.length > 0 && $.inArray(koli[u].Brand,selected) != -1))
{
finalKola.push(koli[u]);
}
else if(kapacitet.length == 0 && selected.length == 0)
{
finalKola.push(koli[u]);
}
else if((kapacitet.length > 0 && $.inArray(koli[u].engineCap,kapacitet) != -1) &&
(selected.length == 0))
{
finalKola.push(koli[u]);
}
else if((selected.length > 0 && $.inArray(koli[u].Brand,selected) != -1) &&
(kapacitet.length == 0))
{
finalKola.push(koli[u]);
}
}
}
I think DataTable is not applying on your table as you are applying datatable on $(document).ready and creating table in your function.
You can apply datatable after you have created the table.
function addTable() {
document.getElementById("results").innerHTML = "";
var myTableDiv = document.getElementById("results")
var tableBody = document.createElement('TBODY')
myTableDiv.border = '1'
myTableDiv.appendChild(tableBody);
var heading = [];
heading[0] = "Бренд"
heading[1] = "Модел"
heading[2] = "Капацитет"
heading[3] = "Коњски сили"
heading[4] = "Цена"
//koloni
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for (a = 0; a < heading.length; a++) {
var th = document.createElement('TH')
th.width = '75';
th.appendChild(document.createTextNode(heading[a]));
tr.appendChild(th);
}
//table rows
for (a = 0; a < finalKola.length; a++) {
var tr = document.createElement('TR');
var td = document.createElement('TD')
td.appendChild(document.createTextNode(finalKola[a].Brand));
tr.appendChild(td);
var td = document.createElement('TD')
td.appendChild(document.createTextNode(finalKola[a].Model));
tr.appendChild(td);
var td = document.createElement('TD')
td.appendChild(document.createTextNode(finalKola[a].engineCap));
tr.appendChild(td);
var td = document.createElement('TD')
td.appendChild(document.createTextNode(finalKola[a].sili));
tr.appendChild(td);
var td = document.createElement('TD')
td.appendChild(document.createTextNode(finalKola[a].amount + " €"));
tr.appendChild(td);
tableBody.appendChild(tr);
}
$('#results').dataTable().fnDestroy();
$('#results').dataTable();
}
Your script is adding tbody before the thead, changed that to append Thead tr first and then tbody.
var selected = [];
var kapacitet = [];
var cena = [];
var hp = [];
var niza = [];
var finalKola = [];
function addTable() {
document.getElementById("results").innerHTML = "";
var myTableDiv = document.getElementById("results")
var tableBody = document.createElement('TBODY')
myTableDiv.border = '1'
var heading = [];
heading[0] = "Бренд"
heading[1] = "Модел"
heading[2] = "Капацитет"
heading[3] = "Коњски сили"
heading[4] = "Цена"
//koloni
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for (a = 0; a < heading.length; a++) {
var th = document.createElement('TH')
th.width = '75';
th.appendChild(document.createTextNode(heading[a]));
tr.appendChild(th);
}
myTableDiv.appendChild(tableBody);
//table rows
for (a = 0; a < finalKola.length; a++) {
var tr = document.createElement('TR');
var td = document.createElement('TD')
td.appendChild(document.createTextNode(finalKola[a].Brand));
tr.appendChild(td);
var td = document.createElement('TD')
td.appendChild(document.createTextNode(finalKola[a].Model));
tr.appendChild(td);
var td = document.createElement('TD')
td.appendChild(document.createTextNode(finalKola[a].engineCap));
tr.appendChild(td);
var td = document.createElement('TD')
td.appendChild(document.createTextNode(finalKola[a].sili));
tr.appendChild(td);
var td = document.createElement('TD')
td.appendChild(document.createTextNode(finalKola[a].amount + " €"));
tr.appendChild(td);
tableBody.appendChild(tr);
}
$(document).ready(function (){
{
$('#results').dataTable();
}
});
}

How to search table with multiple column inputs using jQuery?

Table search functionality for multiple columns using jQuery?
<table>
<tr>
<th><input type="text" id="search" placeholder=" live search"></input></th>
<th><input type="text" id="search" placeholder=" live search"></input></th>
</tr>
<tr><th>Unique ID</th><th>Random ID</th></tr>
<tr><td>214215</td><td>442</td></tr>
<tr><td>1252512</td><td>556</td></tr>
<tr><td>2114</td><td>4666</td></tr>
<tr><td>3245466</td><td>334</td></tr>
<tr><td>24111</td><td>54364</td></tr>
</table>
<br />
<script>
$("#search").on("keyup", function() {
var value = $(this).val();
$("table tr").each(function(index) {
if (index !== 0) {
$row = $(this);
var id = $row.find("td:first").text();
if (id.indexOf(value) !== 0) {
$row.hide();
}
else {
$row.show();
}
}
});
});
</script>
I am trying to implement the search functionality without using jquery plugins..
jsfiddle Link here
http://jsfiddle.net/y9Lxdvps/1/
Use https://api.jquery.com/index/
var inputs = $('table tr:first th input[type=text]');
var trs = $('table tr + tr + tr');
inputs.keyup(function()
{
trs.each(function()
{
var tr = $(this);
var show = inputs.toArray().every(function(input, index)
{
var value = $(input).val();
if (value === '')
{
return true;
}
var number = index + 1;
var td = tr.children('td:nth-child(' + number + ')');
var text = td.text();
return text.indexOf(value) != -1;
});
tr[show ? 'show' : 'hide']();
});
});

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