How do I create the empty table data boxes with JavaScript? - javascript

I want to be able to create the html table like this without using any html and only writing JavaScript.
How do I create the empty table data boxes with JavaScript?
table {
border: 1px solid black;
}
th {
border: 1px solid blue;
}
td {
border: 1px solid red;
}
<!DOCTYPE html>
<html>
<head></head>
<body>
<table>
<tr>
<th>One</th>
<th>Two</th>
<th>Three</th>
</tr>
<tr>
<th>A</th>
<td></td>
<td></td>
</tr>
<tr>
<th>B</th>
<td></td>
<td></td>
</tr>
<tr>
<th>C</th>
<td></td>
<td></td>
</tr>
</table>
</body>
<html>

Try this:
var myTableRows = [
[{"th":"One"},{"th":"Two"},{"th":"Three"}],
[{"th":"A"},{"td":""},{"td":""}],
[{"th":"B"},{"td":""},{"td":""}],
[{"th":"C"},{"td":""},{"td":""}]
];
var table = document.createElement("table");
for(var rowIndex in myTableRows) {
var row = document.createElement("tr");
for(var colIndex in myTableRows[rowIndex]) {
for(var tag in myTableRows[rowIndex][colIndex]) {
var cell = document.createElement(tag);
var cellContents = document.createTextNode(myTableRows[rowIndex][colIndex][tag]);
cell.appendChild(cellContents);
row.appendChild(cell);
}
}
table.appendChild(row);
}
document.body.appendChild(table);

Related

Get prepend() dynamically

I have a table generated in a backend. My task is to wrap text in each header column and add it to each body column cells by using .html() and .prepend(). It works as expected (you will see text in green).
Problem: Tables are generated in a backend, sometimes a table has 3 columns, sometimes 4 columns or more! How to write my Jquery dynamically in order to work on each table.
Please give me a hand. Thanks!
$(document).ready(function() {
var firstHead = $("table thead tr th:first-child").html();
var firstBodyCode = $("<span></span>").text(firstHead);
$('table tbody tr td:first-child').prepend(firstBodyCode);
var secondHead = $("table thead tr th:nth-child(2)").html();
var secondBodyCode = $("<span></span>").text(secondHead);
$('table tbody tr td:nth-child(2)').prepend(secondBodyCode);
});
table {
width: 100%;
border: 1px solid gray
}
span {
color: green
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
</thead>
<tbody>
<tr>
<td>January</td>
<td>$100</td>
</tr>
<tr>
<td>February</td>
<td>$80</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>Sum</td>
<td>$180</td>
</tr>
</tfoot>
</table>
Use a loop to iterate over all the columns.
$(document).ready(function() {
$("table thead tr th").each(function(i) {
let bodyCode = $("<span>", {
text: $(this).text()
});
$(`table tbody tr td:nth-child(${i+1})`).prepend(bodyCode);
});
});
table {
width: 100%;
border: 1px solid gray
}
span {
color: green
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
</thead>
<tbody>
<tr>
<td>January</td>
<td>$100</td>
</tr>
<tr>
<td>February</td>
<td>$80</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>Sum</td>
<td>$180</td>
</tr>
</tfoot>
</table>

how to use bootstrap filter for searching a name by first letter

I am using bootstrap filter for searching. But,for example when I type 'n' it shows all the name having 'n' like nathan, arjan . I don't want that.I want like this : if i type 'n' it will show only the names which starts with 'n' like nathaan,narima.
my blade.php code here:
<input class="form-control" id="myInput" type="text" placeholder="Search..">
<tbody id="myTable">
<tr>
<td>John</td>
</tr>
<tr>
<td>Anja</td>
</tr>
</tbody>
my script part here
<script>
$(document).ready(function(){
$("#myInput").on("keyup", function() {
var value = $(this).val().toLowerCase();
$("#myTable tr").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
});
});
</script>
There is a method called startsWith that you can use. The documentation can be found at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith
<script>
$(document).ready(function(){
$("#myInput").on("keyup", function() {
var value = $(this).val().toLowerCase();
$("#myTable tr").filter(function() {
$(this).toggle($(this).text().toLowerCase().startsWith(value))
});
});
});
</script>
you can change the method if you want.
$("#myInput").bind("keyup", function() {
var text = $(this).val().toLowerCase();
var items = $("tr td");
//first, hide all:
items.parent().hide();
//show only those matching user input:
items.filter(function () {
return $(this).text().toLowerCase().indexOf(text) == 0;
}).parent().show();
});
Another way would be using RegExp:
$(document).ready(function() {
$("#myInput").on("keyup", function() {
var value = $(this).val().toLowerCase();
$("#myTable tr").filter(function() {
/* $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1) */
const searchRegEx = new RegExp(`^${value}`, 'i');
$(this).toggle(searchRegEx.test($(this).text().trim()));
});
});
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
<input class="form-control" id="myInput" type="text" placeholder="Search..">
<table class="table table-bordered">
<tbody id="myTable">
<tr>
<td>John</td>
</tr>
<tr>
<td>Anja</td>
</tr>
</tbody>
</table>
Using .charAt(0) for result set to be filtered with first character match
Basic example from w3schools modified
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
* {
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;
}
</style>
</head>
<body>
<h2>My Customers</h2>
<input type="text" id="myInput" onkeyup="filterBy()" placeholder="Search..." 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>Marimba</td>
<td>Something</td>
</tr>
<tr>
<td>Marimba</td>
<td>Something</td>
</tr>
<tr>
<td>North/South</td>
<td>UK</td>
</tr>
<tr>
<td>Paris specialites</td>
<td>France</td>
</tr>
</table>
<script>
function filterBy() {
var input, filter, table, tr, td, i, txtValue;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
table = document.getElementById("myTable");
tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[0];
if (td) {
txtValue = td.textContent || td.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
if (txtValue.toUpperCase().charAt(0) == filter.charAt(0)) {
tr[i].style.display = "";
}
} else {
tr[i].style.display = "none";
}
if(filter.length == 0)
{
tr[i].style.display = "";
}
}
}
}
</script>
</body>
</html>

jquery find() equivalent for javascript

I have three tables and i want to check wheter they contain a specific element, e.g. a button with the value 'Previous'. I solved it by using the jquery function find and writing a function, but i need to solve this problem without jquery. Is this possible?
var t1 = document.getElementById("table_one");
var t2 = document.getElementById("table_two");
var t3 = document.getElementById("table_three");
has_prev_button(t1);
has_prev_button(t2);
has_prev_button(t3);
function has_prev_button(element)
{
var has_prev_button = false;
var check = $(element).find("input[type=button]");
for (i=0; i<=check.length-1; i++) {
if (check[i].getAttribute("value") == "Previous") {
has_prev_button = true;
}
}
if (has_prev_button) {
document.write("<p>The selected table has a Previous button</p>");
} else {
document.write("<strong><p style='color:red'>The selected table has NO Previous button</p></strong>");
}
}
table {
margin-bottom:40px;
border: 1px solid black;
}
td {
border: 2px solid #D8D8D8;
width: 70px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="table_one">
<tr>
<td>Foo</td>
<td>Bar</td>
<tr>
<tr>
<td><input type="button" value="Previous"></td>
<td><input type="button" value="Next"></td>
</tr>
</table>
<table id="table_two">
<tr>
<td>Foo</td>
<td>Bar</td>
<tr>
<tr>
<td></td>
<td><input type="button" value="Next"></td>
</tr>
</table>
<table id="table_three">
<tr>
<td>Foo</td>
<td>Bar</td>
<tr>
<tr>
<td><input type="button" value="Previous"></td>
<td><input type="button" value="Next"></td>
</tr>
</table>
Use element.querySelectorAll:
var t1 = document.getElementById("table_one");
var t2 = document.getElementById("table_two");
var t3 = document.getElementById("table_three");
has_prev_button(t1);
has_prev_button(t2);
has_prev_button(t3);
function has_prev_button(element)
{
var has_prev_button = false;
var check = element.querySelectorAll("input[type=button]");
for (i=0; i<=check.length-1; i++)
{
if (check[i].value == "Previous")
{
has_prev_button = true;
}
}
if (has_prev_button)
{
document.write("<p>The selected table has a Previous button</p>");
}
else
{
document.write("<strong><p style='color:red'>The selected table has NO Previous button</p></strong>");
}
}
table {
margin-bottom:40px;
border: 1px solid black;
}
td {
border: 2px solid #D8D8D8;
width: 70px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="table_one">
<tr>
<td>Foo</td>
<td>Bar</td>
<tr>
<tr>
<td><input type="button" value="Previous"></td>
<td><input type="button" value="Next"></td>
</tr>
</table>
<table id="table_two">
<tr>
<td>Foo</td>
<td>Bar</td>
<tr>
<tr>
<td></td>
<td><input type="button" value="Next"></td>
</tr>
</table>
<table id="table_three">
<tr>
<td>Foo</td>
<td>Bar</td>
<tr>
<tr>
<td><input type="button" value="Previous"></td>
<td><input type="button" value="Next"></td>
</tr>
</table>
Simply use document.querySelectorAll along with the classes spaced apart.
For example, if I want to find the button in the 3rd section and change its background color:
jQuery
$('.my_sections').eq(2).find('.my_button').css('background', 'pink')
Vanilla JS
document.querySelectorAll('.my_sections .my_button')[2].style.background = 'pink'
Similarly, If I wanted to check how many buttons I had of the my_button class:
document.querySelectorAll('.my_sections .my_button').length

Javascript delete a table tbody tag

I know I can use the following code to remove rows in vanilla Javascript:
var table = document.getElementById('table');
function deleteRow () {
table.deleteRow(1);
};
table { background: #ccc; width: 100%; }
table thead { background: #333; color: #fff; }
table tbody { background: magenta; color: #fff; }
<button onclick="deleteRow()">Delete Row</button>
<table id="table">
<thead>
<tr>
<td>foo</td>
<td>bar</td>
</tr>
</thead>
<tbody>
<tr>
<td>lorem</td>
<td>ipsum</td>
</tr>
</tbody>
<tbody>
<tr>
<td>lorem</td>
<td>ipsum</td>
</tr>
</tbody>
</table>
But this code leaves an empty tbody tag behing. JS has methods for removing thead and tfoot elements, but it seems it's missing a deleteTbody one.
How am I supposed to remove a tbody and all it's contents by using pure javascript only? No jQuery, please!
Try using:
var tbl = document.getElementById("table"); // Get the table
tbl.removeChild(tbl.getElementsByTagName("tbody")[0]); // Remove first instance of body
https://jsfiddle.net/Ltdr2qv4/1/
Use querySelectorAll() to iterate through all TBODY elements, then remove those that have no children:
var table = document.getElementById('table');
function deleteRow() {
table.deleteRow(1);
var tb = document.querySelectorAll('tbody');
for (var i = 0; i < tb.length; i++) {
if (tb[i].children.length === 0) {
tb[i].parentNode.removeChild(tb[i]);
}
}
};
table {
background: #ccc;
width: 100%;
}
table thead {
background: #333;
color: #fff;
}
table tbody {
background: magenta;
color: #fff;
}
<button onclick="deleteRow()">Delete Row</button>
<table id="table">
<thead>
<tr>
<td>foo</td>
<td>bar</td>
</tr>
</thead>
<tbody>
<tr>
<td>lorem</td>
<td>ipsum</td>
</tr>
</tbody>
<tbody>
<tr>
<td>lorem</td>
<td>ipsum</td>
</tr>
</tbody>
</table>
If you want to remove the tbody tag, you could select the row itself rather than the table, then use the removeChild function.
var table = document.getElementById('table');
var row = document.getElementsByTagName('tbody')[0];
function deleteRow () {
row.parentNode.removeChild(row);
};
There is no deleteTbody but there is removeChild:
var parent = document.getElementById("parent-id");
var child = document.getElementById("child-id");
parent.removeChild(child);
I hope it will help you. I am sorry. It is too late to answer.
tbody-data is tbody's id value.
$("#tbody-data tr").remove();

Clicked Table Row Returns NaN

I am trying to identify as to what row number the user clicks on and to alert them. I wanted to exempt the table headers from being counted so I have intentionally used the this.rowIndex - 1 but when I click on any row, the alert box is returning a NaN value.
How do you fix this?
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
#mstrTable {
border: 1px solid black
}
#mstrTable td, th {
border: 1px solid black
}
#mstrTable tr.normal td {
color: black;
background-color: white;
}
#mstrTable tr.highlighted td {
color: white;
background-color: gray;
}
</style>
</head>
<body>
<table id="mstrTable">
<thead>
<tr>
<th>File Number</th>
<th>Date1</th>
<th>Date2</th>
<th>Status</th>
<th>Num.</th>
</tr>
</thead>
<tbody>
<tr>
<td>KABC</td>
<td>09/12/2002</td>
<td>09/12/2002</td>
<td>Submitted</td>
<td>0</td>
</tr>
<tr>
<td>KCBS</td>
<td>09/11/2002</td>
<td>09/11/2002</td>
<td>Approved</td>
<td>1 </td>
</tr>
<tr>
<td>WFLA</td>
<td>09/11/2002</td>
<td>09/11/2002</td>
<td>Submitted</td>
<td>2</td>
</tr>
<tr>
<td>WTSP</td>
<td>09/15/2002</td>
<td>09/15/2002</td>
<td>In-Progress</td>
<td>3</td>
</tr>
</tbody>
</table>
<script type="text/javascript">
(
function( )
{
var trows = document.getElementById("mstrTable").rows;
for ( var t = 1; t < trows.length; ++t )
{
trow = trows[t];
trow.className = "normal";
trow.onclick = highlightRow;
}
function highlightRow(e)
{
alert('Row is ' + this.rowIndex-1)
for ( var t = 1; t < trows.length; ++t )
{
trow = trows[t];
trow.className = ( trow == this && trow.className != "highlighted") ? "highlighted" : "normal";
}
}
}
)();
</script>
</body>
</html>
Put parentheses around math operations so they take precedence over string concatenation.
alert('Row is ' + (this.rowIndex-1))
Fiddle
Change it to this.rowIndex instead of this.rowIndex-1.

Categories