Append rows in the table one by one - javascript

I want to append rows to the table one by one, not all at once. Problem i'm facing is, no. of rows is very large, say 10,000. It append all the rows at once after loop terminates. I want it to work like, with each iteration, it should append the row to the table.
$(document).ready(function(){
for(var i=0;i<1000;i++){
var name = "name "+i;
var email = "email"+i+"#vvv.com";
var markup = "<tr><td><input type='checkbox' name='record'></td><td>" + name + "</td><td>" + email + "</td></tr>";
//$("table tbody").append(markup);
//$("tbody").parent("table").append(markup);
$("tbody").after(markup);
}
});
table{
width: 100%;
margin-bottom: 20px;
border-collapse: collapse;
}
table, th, td{
border: 1px solid #cdcdcd;
}
table th, table td{
padding: 10px;
text-align: left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>Select</th>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox" name="record"></td>
<td>Name</td>
<td>email#vvv.com</td>
</tr>
</tbody>
</table>

I see what you are trying to do. You may try to use setTimeout to achieve this. You are trying to loop an array but in your code you are just generating new rows. So I tried to implement your code into this solution. If you are trying to loop an array you need to modify this.
$(document).ready(function(){
appendOneByOne(1000)
});
function appendOneByOne(i){
if(i !== 0){
setTimeout(function(){
var name = "name "+i;
var email = "email"+i+"#vvv.com";
var markup = "<tr><td><input type='checkbox' name='record'></td><td>" + name + "</td><td>" + email + "</td></tr>";
$("tbody").after(markup);
appendOneByOne(--i)
});
}
}
You can also use window.requestAnimationFrame(); but take care for cross-browser issues.

Related

setting a value in the dropdowns in table based on imported values [javascript, jquery]

I have a table that is filled dynamically with a csv file. I created a table that inside itself has dropdowns in some columns.
What I want to do now is to check if a value exists in the cell where the dropdown is supposed to be, if so to check if it exists in the dropdownlist if yes then set this as selected in dropdown list otherwise selected is at default value and the cell gets red margine around.
Here is a jsFiddle with an example as how my code currently looks like:
https://jsfiddle.net/r236uy5k/
EDIT : I corrected my jsfiddle:
https://jsfiddle.net/kcau7jhd/
$(function(){
var firstDDM = ['aaa','bbb','ccc','ddd'];
var firstshortcut = ['a','b','c','d'];
var option = "",
select = "";
for(var i=0; i<firstDDM.length;i++){
option += '<option value="'+ firstshortcut[i] + '">' + firstDDM[i] + '</option>';
}
select = '<select class="firstDDM" type="firstDDM">' + option + '</select>';
$("tr").each(function() {
$(this).find("td:eq(3)").append(select);
});
});
$(function(){
var secondDDM = ['Default','AAA','BBB','B1','C'];
var secondshortcut = ['Default','a','b','b1','c'];
var option = "",
select = "";
for(var i=0; i<secondDDM.length;i++){
option += '<option value="'+ secondshortcut[i] + '">' + secondDDM[i] + '</option>';
}
select = '<select class="secondDDM" type="secondDDM">' + option + '</select>';
$("tr").each(function() {
$(this).find("td:eq(5)").append(select);
});
});
$("#addRow").click(function(){
$("#my_id").each(function(){
var tds='<tr>';
jQuery.each($('tr:last th', this), function(){
tds += '<th>' +'<input type="checkbox" name="record" tittle="Delete this row"></input>' + '</th>';
});
jQuery.each($('tr:last td', this), function(){
if($('select',this).length){
tds+= '<td>' + $(this).html() + '</td>';
}else{
tds+= '<td></td>';
}
});
tds+= '</tr>';
$('tbody',this).append(tds);
$('#my_id tbody tr:last').attr("contentEditable", true);
});
});
//for the columns that need to be imported with dropdowns create editable option - temporarlly
$(function() {
$("tr").each(function() {
$(this).find("td:eq(3), td:eq(4),td:eq(5)").attr("contentEditable", true);
});
});
//Find and remove selected table rows
$('#delete-row').click(function(){
var r = confirm('Are you sure you want to delete them all?');
$("tbody").find('input[name="record"]').each(function(){
if($(this).is(":checked")){
if(r == true){
$(this).parents("tr").remove();
}else{
return false;
}
}
});
});
table {
border-collapse: collapse;
border: 1px black solid;
font: 12px sans-serif;
width: 100%;
table-layout:auto;
}
td {
border: 1px black solid;
text-align: left;
padding: 2px;
}
thead:hover{
text-decoration: none !important;
}
thead tr:first-child{
color:white;
text-align: center;
background-color: #5bc0de;
padding: 10px;
}
tr:nth-child(even){
background-color: #f2f2f2
}
tr:hover{
background-color: #5bc0de;
}
button{
display: inline;
padding: 50px;
}
input button{
display: inline;
}
.dropbtn{
background-color: blue;
}
.table-responsive {
overflow-y: auto;
height: 800px;
}
.table-responsive table {
border-collapse: collapse;
width: 100%;
}
.table-responsive thead th{
position: sticky;
top: 0;
background-color: #5bc0de;
padding: 2px;
}
::-webkit-scrollbar {
width: 12px;
}
::-webkit-scrollbar-thumb {
background-color: darkgrey;
outline: 1px solid slategrey;
}
.myButtons{
display: inline;
padding: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<head>
<title>Filtered CSV File</title>
</head>
<body>
<h1>
Filtered CSV FIle
</h1>
<br/>
<br/>
<div class="myButtons">
<input type="button" value="Add new row" class="btn btn-info" id="addRow">
<input type="button" value="Delete rows" id="delete-row" class="btn btn-info">
</div>
<br/>
<div class="table-responsive">
<table class="dataframe my_class" id="my_id">
<thead>
<tr style="text-align:right;">
<th> </th>
<th>col1</th>
<th>col2</th>
<th>col3</th>
<th>col4</th>
<th>col5</th>
<th>col6</th>
<th>col7</th>
<th>col8</th>
</tr>
</thead>
<tbody>
<tr>
<th>1</th>
<td>row1</td>
<td>row1</td>
<td>row1</td>
<td></td>
<td>row1</td>
<td>B1</td>
<td>row1</td>
<td>row1</td>
</tr>
<tr>
<th>2</th>
<td>row2</td>
<td>row2</td>
<td>row2</td>
<td></td>
<td>row2</td>
<td>AAA</td>
<td>row2</td>
<td>row2</td>
</tr>
<tr>
<th>3</th>
<td>row3</td>
<td>row3</td>
<td>row3</td>
<td></td>
<td>row3</td>
<td>C</td>
<td>row3</td>
<td>row3</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
You can edit the select text you are entering. Following are the things which I think you want to achieve:
Identify if the dropdown has a certain value and preselect them if possible.
If the dropdown does not have correct value for pre selection then mark them as error field.
If the above mentioned points are incorrect please let me know i will make the relevant changes which are required.
I have added a condition check if (firstshortcut[i] == $(this).find("td:eq(3)")[0].innerHTML) you can replace it with any condition that you want.
Replace the following jquery snippets
$("tr").each(function () {
var option = "",
select = "",
classObject = '',
isSelected = false;
if($(this).find("td:eq(3)")[0]){
for (var i = 0; i < firstDDM.length; i++) {
if (firstshortcut[i] == $(this).find("td:eq(3)")[0].innerHTML) {
option += '<option selected="selected" value="' + firstshortcut[i] + '">' + firstDDM[i] + '</option>';
isSelected = true;
}
else
option += '<option value="' + firstshortcut[i] + '">' + firstDDM[i] + '</option>';
}
classObject = !isSelected ? 'errorDropDown' : '';
select = '<select class="firstDDM' + ' ' + classObject + '" type="firstDDM">' + option + '</select>'
$(this).find("td:eq(3)").append(select);
}
});
Add this class to the css file:
.errorDropDown {border: 1px solid red;}

How to break JSON data in multiple pages?

I have a html code and it it working fine for small json file and showing data in html table properly. But my problem is now that i have a big json file around 15000 html table row. So my page is not responding. How can i break 100 result per page till last result. I am sharing my html code.Please add some code in my html file and paste in answer section
<html>
<header><title>Welcome</title></header>
<body>
<!--javascript make append table data-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$("#userdata tbody").empty();
$(function() {
var user = document.getElementById("userId").value;
var category = location.search.split('id=')[1]
$.getJSON('abc.php',{"userId":user,"categoryId":category}, function(data) {
$.each(data.videos , function(i, v) {
var link = "youtube.php?id=youtu.be/"+ v.video;
var tblRows = "<tr>" + "<td>" + v.videoName + "</td>" + "<td>" + v.date + "</td>" +"<td>"+ v.time + "</td>" + "<td>" + v.videoDuration + "</td>" + "<td><a target='_blank' href='"+link+"'>"+"WATCH/DOWNLOAD"+"</a></td>" + "</tr>";
$(tblRows).appendTo("#userdata tbody");
});
});
$.getJSON('crp.php',{"userId":user,"categoryId":category}, function(data) {
$.each(data.other , function(i, f) {
var link =f.pdf;
tblRows2 = "<tr>" + "<td>" + f.dateText + "</td>" + "<td>" + f.textMessage + "</td>" + "<td><a target='_blank' href='"+link+"'>"+"Click here to Download"+"</a></td>" + "</tr>";
$(tblRows2).appendTo("#userdata2 tbody");
});
});
});
</script>
<!--javascript append table data ended -->
<!-- user form -->
<form>
<input id='userId' type="hidden" value="500" placeholder="Enter Your User Id" name="userId" autofocus required>
</form>
<!-- user form -->
<!--table-->
<h1>VIDEO LIST</h1>
<!--<style>
.wrapper {
table tr td:nth-child(5) {
background: white;
}
}
.profile {
table, th, tr {
border: 5px solid green;
background:5px black;
color: white;
font-weight: bold;
}
}
}
</style>-->
<!--<style>
.button {
border: 5px solid green;
background:5px black;
color: white;
font-weight: bold;
tr:nth-of-type(odd) {
background: #eee;
}
}
</style>-->
<table class="button" id= "userdata" width="100%" border="20">
<thead>
<th>VIDEO NAME</th>
<th>DATE</th>
<th>TIME</th>
<th>DURATION</th>
<th>LINK</th>
</thead>
<tbody>
</tbody>
</table>
<!--table data end-->
<!--table-->
</body>
<body>
<style>
table tr td:nth-last-of-type(1) {
background: white;
}
table, th, tr {
border: 5px solid green;
background:5px black;
color: white;
font-weight: bold;
}
</style>
<h1>PDF LIST</h1>
<div class="wrapper2">
<div class="profile2">
<table id= "userdata2" width="100%" border="20">
<thead>
<th>DATE</th>
<th>NAME</th>
<th>LINK</th>
</thead>
<tbody>
</tbody>
</table>
</tr>
</div>
</div>
</body>
</html>
you have multiple options
1-use pagination like 1,2,3,4,etc
->this can be done using js and php or php with sql setting limit on your query and shift it when you choose another page
2-lazy loading on scroll -> this can be done using js
example using php with my sql
https://www.tutorialspoint.com/php/mysql_paging_php.htm

How to change the color of particular characters of string using JavaScript?

I am using table search functionality using this code -
https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_filter_table.
When user search for any row data using some search characters like "Jac", I want to change the color of these 3 characters only and want to show entire row. How can I change the color of these 3 characters? Or search input characters?
EDIT - My code is:
$("#searchBox").keyup(function() {
var input, filter, table, tr, td, i;
input = document.getElementById("searchBox");
filter = input.value.toUpperCase();
if (filter.length > 1) {
table = document.getElementById("myTable");
tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[1];
if (td) {
if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
var regx = new RegExp(filter, "g");
var newstring = td.innerHTML.replace(regx, '<span class="highlight">' + filter + '</span>');
td.innerHTML = newstring;
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
} else {
table = document.getElementById("myTable");
tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++) {
tr[i].style.display = "";
}
}
});
Output of above code is not correct. It will work only when length of search string is more than 1. If I enter 3 characters it failed.
Might be an overkill approach. But this how I got it working.
The technique:
1- Get the original table (as a whole DOM) into a JS variable
2- Clone that variable into another JS variable.
3- The clone is used as a reference. Will remain intact never be modified.
4- The highlight works by extracting the found phrase, wrap with a <span> having that span is given a certain CSS to stand out from the rest of the text.
The reason behind this is that, if we edit the original table, and then we try to search again, the HTML tag that got inserted will be included in the searched terms and therefore, the search will break down.
We will be searching the clone always, then will get the text from the clone, process it, and then apply the new processed phrase to the original table. In other words, If the searched phrase is found in the clone object, its content will be copied over to the original table.
If I were to do this again, I would replace the whole thing with JQuery. But anyhow, this code needs to be optimized.
var originalTable = document.getElementById("myTable");
var realTr = originalTable.getElementsByTagName("tr");
var cloneTable = originalTable.cloneNode(true);
var cloneTr = cloneTable.getElementsByTagName("tr");
function myFunction() {
var input, filter, cloneTd, cloneTdValue, realTd, i, inputValue, inputValueUpper;
input = document.getElementById("myInput");
inputValue = input.value;
inputValueUpper = inputValue.toUpperCase();
for (i = 0; i < cloneTr.length; i++) {
cloneTd = cloneTr[i].getElementsByTagName("td")[0];
if (cloneTd) {
var cloneTdValue = cloneTd.innerHTML;
var cloneTdValueUpper = cloneTdValue.toUpperCase();
var index = cloneTdValueUpper.indexOf(inputValueUpper);
if (index > -1) {
var newStr = wrapStuff(inputValue, cloneTdValue, index);
realTr[i].style.display = "";
realTd = realTr[i].getElementsByTagName("td")[0];
realTd.innerHTML = newStr;
} else {
realTr[i].style.display = "none";
}
}
}
}
function wrapStuff(input, tdStr, index) {
if (input.length === 0)
{
return tdStr;
}
var before, after, searched, extractLen, extractedVal, newString;
extractLen = index + input.length;
before = tdStr.substring(0, index);
after = tdStr.substring(extractLen, tdStr.length);
var newIndex = after.indexOf(input);
//Recursive function: yeah, my head got spinning.
//this is to apply the same code to the second half of the spliced string, because indexOf will only find the first occurance.
if (newIndex > -1) {
after = wrapStuff(input, after, newIndex);
}
extractedVal = tdStr.substring(index, extractLen);
newString = before + "<span class=\"highlight\">" + extractedVal + "</span>" + after;
return newString;
}
* {
box-sizing: border-box;
}
#myInput {
background-image: url('/css/searchicon.png');
background-position: 10px 10px;
background-repeat: no-repeat;
width: 100%;
font-size: 16px;
padding: 12px 20px 12px 40px;
border: 1px solid #ddd;
margin-bottom: 12px;
}
#myTable {
border-collapse: collapse;
width: 100%;
border: 1px solid #ddd;
font-size: 18px;
}
#myTable th, #myTable td {
text-align: left;
padding: 12px;
}
#myTable tr {
border-bottom: 1px solid #ddd;
}
#myTable tr.header, #myTable tr:hover {
background-color: #f1f1f1;
}
.highlight {
color: red;
}
<body>
<h2>My Customers</h2>
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names.." title="Type in a name">
<table id="myTable">
<tr class="header">
<th style="width:60%;">Name</th>
<th style="width:40%;">Country</th>
</tr>
<tr>
<td>Alfreds Futterkiste</td>
<td>Germany</td>
</tr>
<tr>
<td>Berglunds snabbkop</td>
<td>Sweden</td>
</tr>
<tr>
<td>Island Trading</td>
<td>UK</td>
</tr>
<tr>
<td>Koniglich Essen</td>
<td>Germany</td>
</tr>
<tr>
<td>Laughing Bacchus Winecellars</td>
<td>Canada</td>
</tr>
<tr>
<td>Magazzini Alimentari Riuniti</td>
<td>Italy</td>
</tr>
<tr>
<td>North/South</td>
<td>UK</td>
</tr>
<tr>
<td>Paris specialites</td>
<td>France</td>
</tr>
</table>
<script>
</script>
</body>
Capture the search phrase (the word you are searching or looking for). Capture the search area (the table or paragraph you are searching into). Look into the search area to see if you can find the search phrase. Once it exists, replace with a string that has an HTML element tag surrounding it.
Replace the searched word with the same word but wrapped in a span that has certain CSS class. Use CSS to customize the look.
var toLookInto = $("#toLookInto").html();
$("#toFind").on("keyup", function() {
var toFind = $("#toFind").val();
var regx = new RegExp(toFind, "g");
var newstring = toLookInto.replace(regx, '<span class="highlight">' + toFind + '</span>')
$("#toLookInto").html(newstring)
});
.highlight {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<p id="toLookInto">
dummy text foo bar cat mewo dummy text foo bar cat mewo dummy text foo something odd bar cat mewo dummy text foo bar cat mewo
</p>
<br>
<input type "text" id="toFind" />
<lable>The text field will be triggered on every key pressed</label>

Using not(selector) on dynamically create element

The code basically edit a table cell.
I want to use the not() method so that everytime I click outside the temporary input created I replace it with a table cell. I guess the code run in a block and doesn't detect any input with an id of "replace" so how can I fix that ?
Also I want to store the element (th or td) that fire the first event(dblclick) so that I can use it to replace the input with the right type of cell but it seems to only stores the element that first triggers the event and I don't really understand why.
Full code here
$(function () {
$(document).on("dblclick", "th, td", function (event) {
var cellText = $(this).text();
$(this).replaceWith("<input type='text' id='replace' value='" + cellText + "'>");
var $typeCell = $(event.currentTarget); // Store element which trigger the event
$("body").not("#replace").on("click", function () { // .not() method
cellText = $("#replace").val();
if ($typeCell.is("th")) {
$("#replace").replaceWith("<th scope='col'>" + cellText + "</th>");
}
else {
$("#replace").replaceWith("<td>" + cellText + "</td>");
}
});
});
});
I have modified HTML and JavaScript to avoid any possible errors. The correct practice is to wrap all th's in a thead and all td's in tbody.
$(document).on("dblclick", "th, td", function(event) {
var cellText = $(this).text();
$(this).replaceWith("<input type='text' id='replace' value='" + cellText + "'>");
});
$("body").on("click", function() {
if (event.target.id != 'replace' && $('#replace').length != 0) {
var cellText = $("#replace").val();
if ($('#replace').parents().is('thead'))
$("#replace").replaceWith("<th scope='col'>" + cellText + "</th>");
else
$("#replace").replaceWith("<td>" + cellText + "</td>");
}
});
table {
border-collapse: collapse;
margin: 20px;
min-width: 100px;
}
table,
th,
td {
border: 1px solid grey;
padding: 4px;
}
th {
background: springgreen;
}
tr:nth-child(odd) {
background: rgba(0, 255, 127, 0.3);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<table>
<thead>
<tr>
<th scope="col">Uno</th>
<th scope="col">Dos</th>
<th scope="col">Tres</th>
</tr>
</thead>
<tbody>
<tr>
<td>Data1</td>
<td>Data2</td>
<td>Data3</td>
</tr>
<tr>
<td>Data4</td>
<td>Data5</td>
<td>Data6</td>
</tr>
</tbody>
</table>
</div>

Why my css display Irregular?

My HTML Code is like this :
...
<button class="save bookbtn mt1">More</button>
...
<div class="cruisedropd">
<div id="loading" class="loading"></div>
</div>
...
My Javascript Code is like this
...
$('.save').click(function () {
...
success: function (response) {
...
var elem = $parent.find('.loading').empty();
elem.append('<table class="table">\
<tbody>\
<tr>\
<th>Status</th>\
<th>Room Grade</th>\
<th>Meal</th>\
<th>Per Room.Night</th>\
<th>Cancel Policy</th>\
<th>Book It</th>\
</tr>')
for(var i=0; i<response.SearchAvailResponse.Hotel.length; i++){ //make sure to use var
elem.append('<tr>\
<td>' + Status + '</td>\
<td>' + RmGrade + '</td>\
<td>' + Meal + '</td>\
<td>' + Currency + ' ' + TotalRate + '</td>\
<td>Cancel Policy</td>\
<td>\
<form action="details.html">\
<button class="bookbtn mt1" type="submit">Book</button>\
</form>\
</td>\
</tr>'); //add the new content
}
elem.append('</tbody>\
</table>')
...
}
...
}
...
The View is like this : http://imgur.com/1OIVGGU
Why my css display irregular?
Any solution to solve my problem?
Thank you very much
The short answer is that you can not build a table in that way.
Your first snippet of code appends the table headers. Then DOM automatically adds closing table tag.
Your next snippet of code runs a loop to append rows. However, the table was already created in the previous step.
So you end up with 2 tables in the DOM which don't align.
Suggest building the table as a string and then appending that string to the div so that the DOM builds a single table.
UPDATE:
This code, in response to OP comment, demonstrates how to make the original code work with just 3 very minor changes. The table is first built as a string. The string is then appended to the innerHTML of the container. Doing it this way prevents the DOM from prematurely adding a closing tag to the table element, as was the case in the original code.
And now the table header and rows align, which was the stated problem.
Click the "Run code snippet" button to see it work.
function success() {
var html =('<table class="table">\
<tbody>\
<tr>\
<th>Status</th>\
<th>Room Grade</th>\
<th>Meal</th>\
<th>Per Room.Night</th>\
<th>Cancel Policy</th>\
<th>Book It</th>\
</tr>')
for(var i=0; i<10; i++){
html += ('<tr>\
<td>' + Status + '</td>\
<td>' + RmGrade + '</td>\
<td>' + Meal + '</td>\
<td>' + Currency + ' ' + TotalRate + '</td>\
<td>Cancel Policy</td>\
<td>\
<form action="details.html">\
<button class="bookbtn mt1" type="submit">Book</button>\
</form>\
</td>\
</tr>');
}
html += ('</tbody>\
</table>');
$('#container').html( html );
}
// test data
var Status="OK", RmGrade=5, Meal="Yes", Currency="Euro", TotalRate="100";
success();
td,th {padding:2px; border:1px gray solid;}
th {background-color: peru; }
table {border-collapse: collapse;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<div id="container"></div>
Do you mean that the table content is not aligned properly? Verify your CSS that there is no width property on your TD element.
HTML:
<table>
<tr>
<th>Test1</th>
<th>Test2</th>
<th>Test3</th>
</tr>
<tr>
<td>Wat</td>
<td>Wat2</td>
<td>Wat3</td>
</tr>
<tr>
<td>Foo</td>
<td>Foo2</td>
<td>Foo3</td>
</tr>
</table>
CSS:
table {
width: 100%;
}
th, td {
text-align: left;
}
Fiddle: https://jsfiddle.net/vup7vz1k/1/

Categories