Creating common class in javascript - javascript

I have one html page with some div and table inside div. Getting data by using XHTMLREQUEST. How can I make this to wrapper class so I can use it whenever I want in project with some id.
I can create div with id and use that particularturl for the loading data. How can I make it common so I can use it anywhere.
My htmlcode:
<html>
<head>
<style>
* {
box-sizing: border-box;
}
#myInput {
background-image: url('/css/searchicon.png');
background-position: 10px 10px;
background-repeat: no-repeat;
width: 30%;
font-size: 16px;
padding: 12px 20px 12px 40px;
border: 1px solid #ddd;
margin-bottom: 12px;
}
#myTable {
border-collapse: collapse;
width: 30%;
height : 30%;
overflow-y:auto;
border: 1px solid #ddd;
font-size: 18px;
display: none;
margin-top:-12px;
}
#myTable th, #myTable td {
text-align: left;
padding: 12px;
width : 10%;
}
#myTable tr {
border-bottom: 1px solid #ddd;
order-top: 1px solid #ddd;
}
#myTable tr.header, #myTable tr:hover {
background-color: #f1f1f1;
}
#myInput:focus + #myTable{
display: block;
}
#myTable:hover{
display: block;
}
</style>
</head>
<body>
<h2>My Customers</h2>
<input type="text" id="myInput" onkeyup="myFunction()" title="Type in a name">
<table id="myTable">
<tr class="header"></tr>
<tr><td>Germany</td></tr>
<tr><td>Sweden</td></tr>
<tr><td>UK</td></tr>
<tr><td>Germany</td></tr>
<tr><td>Canada</td></tr>
<tr><td>Italy</td></tr>
<tr><td>UK</td></tr>
<tr><td>France</td></tr>
</table>
<script>
function myFunction() {
var input, filter, table, tr, td, i;
table = document.getElementById("myTable");
tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[0];
if (td) {
if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}
document.querySelectorAll('#myTable tr:not(.header)').forEach(function(_tr){
_tr.addEventListener('click',function(){
document.getElementById('myInput').value += " "+ this.getElementsByTagName('td')[0].textContent;
});
});
</script>
</body>
</html>
This is how I am loading the data.
function foo(callback) {
var httpRequest = new XMLHttpRequest();
httpRequest.open('GET', "data.json",true);
httpRequest.onreadystatechange = function () {
if(httpRequest.readyState === XMLHttpRequest.DONE && httpRequest.status === 200) {
// trigger your callback function
callback(httpRequest.responseText);
}
};
httpRequest.send();
}
foo(function(data) {
var jsonc = JSON.parse(data);
var new_opt="";
for(i=0;i<jsonc.length;i++)
{
new_opt+='<option value="'+jsonc[i]['VALUE']+'">'+jsonc[i]['VALUE']+'</option>';
}
document.getElementById('choose').innerHTML =new_opt;
});
I know this code I can use only for this place. But I want same idea for another div also. I just wann pass some id and create the same div which I using here.
Can anybody help me in Javascript class which should be generic class.

Related

Remove entire table when there is no input in searchbox?

I have been twisting my head around on this and I can't seem to fix it.
I have not coded much, but wanting to learn. However, I am trying to make a table in which when there is no input the entire table vanishes.
As of now I have managed to get it so that it starts as vanished, and that when information is inserted into the search box the non-relevant lines dissapear. However, when all text in the search box is removed the entire table is showing. I want the table to stay hidden when there is no text that matches.
Would love to get any feedback on what I am doing wrong here.
function performSearch() {
// Declare search string
var filter = searchBox.value.toUpperCase();
// Loop through first tbody's rows
for (var rowI = 0; rowI < trs.length; rowI++) {
// define the row's cells
var tds = trs[rowI].getElementsByTagName("td");
// hide the row
trs[rowI].style.display = "none";
// loop through row cells
for (var cellI = 0; cellI < tds.length; cellI++) {
// if there's a match
if (tds[cellI].innerHTML.toUpperCase().indexOf(filter) > -1)
{
// show the row
myTable.style.display = "table";
trs[rowI].style.display = "";
// skip to the next row
continue;
}
}
}
}
// declare elements
const searchBox = document.getElementById('searchBox');
const table = document.getElementById("myTable");
const trs = table.tBodies[0].getElementsByTagName("tr");
// add event listener to search box
searchBox.addEventListener('keyup', performSearch);
* {
box-sizing: border-box;
}
#searchBox {
background-image: url('/css/searchicon.png');
background-position: 10px 10px;
background-repeat: no-repeat;
width: 30%;
font-size: 16px;
padding: 12px 20px 12px 40px;
border: 1px solid #ddd;
margin-bottom: 12px;
position: relative;
top: 50%;
left: 50%;
margin-right: -50%;
transform: translate(-50%, -50%);
}
#myTable {
border-collapse: collapse;
width: 80%;
border: 1px solid #ddd;
font-size: 18px;
position: relative;
left: 10%;
display: none;
}
#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;
}
#Overskrift {
width: 100%;
text-align-last: center;
font-size: 40px;
}
<input class="form-control" type="text" id="searchBox" placeholder="Search ..." onkeyup="searchTableColumns()">
<table id="myTable">
<thead>
<tr class="header">
<th onclick="sortTable(0)" style="width:35%;">Fagnavn</th>
<th onclick="sortTable(1)" style="width:21%;">LK20</th>
<th onclick="sortTable(2)" style="width:21%;">LK06</th>
<th onclick="sortTable(3)" style="width:21%;">R94</th>
</tr>
</thead>
<tbody>
<tr>
<td>Pika</td>
<td>Chu</td>
<td>Poke</td>
<td>Mon</td>
</tr>
<tr>
<td>Temporary</td>
<td>Text</td>
<td>Fields</td>
<td>Here</td>
</tr>
</tbody>
</table>
There is a simple solution for this. Just add a check to the end your performSearch function:
if (searchBox.value === ''){
table.style.display='none';
}
else {
table.style.display='table';
}
You can also check it here:
https://codepen.io/serazoltan/pen/dyZRprb

How to make filter/search bar search only when 3 characters has been entered?

I have here a search bar from w3schools website which I have tweaked.
Right now, it will show all results at the first letter entered which is slowing down my site since there's more than 5000+ results in one go.
I wonder how can I make this search ONLY after 3 (or 4-5) characters/letters have been inputted?
Here's the DEMO
Here's the script so far:
<script>
document.addEventListener("DOMContentLoaded", function() {
var $input = document.getElementById("myInput"),
$table = document.getElementById("myTable"),
$$tr = $table.querySelectorAll("tbody tr"),
$noResults = $table.querySelector("tfoot tr");
for (var i = 0; i < $$tr.length; i++) {
var $$td = $$tr[i].querySelectorAll("td"),
name = $$td[0].innerText,
country = $$td[1].innerText;
$$tr[i].normalizedValue = normalizeStr( name + " " + country );
}
$input.addEventListener("input", performSearch);
function performSearch() {
var filter = normalizeStr(this.value),
resultCount = 0;
for (var i = 0; i < $$tr.length; i++) {
var isMatch = filter.length > 0 && $$tr[i].normalizedValue.includes(filter);
if (isMatch) { resultCount++; }
$$tr[i].classList[isMatch ? "add" : "remove"]("visible");
}
var showNoResultsMessage = resultCount === 0 && filter.length > 0;
$noResults.classList[showNoResultsMessage ? "add" : "remove"]("visible");
}
function normalizeStr(str) {
return (str || '').toUpperCase().trim();
}
});
</script>
Here's the CSS:
#myInput{
font-size:15px;
width:90%;
padding: 5px;
border-radius: 4px;
border: none;
margin-bottom: 1px;
background: #f5f5f5;
outline: none;
color: #000000;
}
input::placeholder {
color: #000000;
}
#myTable{
border-collapse:collapse;
width:90%;
font-size:14px;
font-family: "Poppins", sans-serif;
}
#myTable td, #myTable th{
text-align:left;
padding:8px;
}
#myTable td a
}
#myTable tr{
border-bottom:1px solid #222222;
}
#myTable thead tr, /* notice the use of thead */
#myTable tr:hover {
background-color: #e0f2f1;
text-decoration: none;
}
#myTable tbody tr {
display: none; /* Hide rows by default */
}
#myTable tbody tr.visible {
display: table-row; /* Show them when they match */
}
#myTable tfoot tr:not(.visible) {
display: none; /* Hide the "no results" message if not visible */
}
#myTable tfoot td {
text-align: center;
}
input:focus,
select:focus,
textarea:focus,
button:focus {
outline: none;
}
and the HTML:
<input class="mt-4 mx-auto" type="text" id="myInput" placeholder="Search"/>
<table class="mb-5" id="myTable" align="center"><tbody>
<tr><td><b>BM: </b>Quip</td><td><p hidden></p></td></tr>
<tr><td><b>BM: </b>Facebook</td><td><p hidden></p></td></tr>
<tr><td><b>BM: </b>Instagram</td><td><p hidden></p></td></tr>
<tr><td><b>BM: </b>Twitter</td><td><p hidden></p></td></tr>
<tr><td><b>BM: </b>Telegram</td><td><p hidden></p></td></tr>
<tr><td><b>BM: </b>Spotify</td><td><p hidden></p></td></tr>
</table>
I would really appreciate all the help. Cheers! :)
HTML:
<input type="text" id="input">
JS:
document.addEventListener('DOMContentLoaded', function() {
document.getElementById('input').addEventListener('input', performSearch);
function performSearch() {
if (this.value.length < 3) return;
// search code
}
});
If you have any questions, ask.

Personalizing table headers, create pagination, sorting and filter with HTML Table Using JavaScript

<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">
#container,#buttondiv{
margin: 0 auto;
width: 80%;
overflow: auto;
}
table.gridtable {
margin: 0 auto;
width: 95%;
overflow: auto;;
font-family: helvetica, arial, sans-serial;
font-size: 14px;
color: #333333;
border-width: 1px;
border-color: #666666;
border-collapse: collapse;
text-align: center;
}
table.gridtable th {
border-width: 1px;
padding: 8px;
border-style: solid;
border-color: #666666;
background-color: #F6B4A5;
}
table.gridtable td{
border-width: 1px;
padding: 8px;
border-style: solid;
border-color: #666666;
}
</style>
</head>
<body>
<p align="center"><input type="file" id="fileUpload" />
<input type="button" id="upload" value="Upload" onclick="Upload()" /></p>
<hr />
<div id="dvCSV">
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
function Upload() {
var fileUpload = document.getElementById("fileUpload");
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.csv|.txt)$/;
if (regex.test(fileUpload.value.toLowerCase())) {
if (typeof (FileReader) != "undefined") {
var reader = new FileReader();
reader.onload = function (e) {
var table = document.createElement("table");
var rows = e.target.result.split("\n");
for (var i = 0; i < rows.length; i++) {
var cells = rows[i].split(",");
if (cells.length > 1) {
var row = table.insertRow(-1);
for (var j = 0; j < cells.length; j++) {
var cell = row.insertCell(-1);
cell.innerHTML = cells[j];
}
}
}
var dvCSV = document.getElementById("dvCSV");
dvCSV.innerHTML = "";
dvCSV.appendChild(table);
}
reader.readAsText(fileUpload.files[0]);
} else {
alert("This browser does not support HTML5.");
}
} else {
alert("Please upload a valid CSV file.");
}
}
</script>
</body>
</html>
I'm new in javascript and in the above code, I am loading a CSV file into HTML table. But I am getting the table headers as they are the CSV files. However, I would like to personalize them when displaying. For example, in the CSV file, I have pr_id and I would like to display it as PR ID in the HTML table.
Also, I would like to add a javascript code that will create pagination, sorting and filter with HTML Table.

Javascript uploading file alignment

In the above image the delete button need to align properly. in my code it get align based on file name length.
<script>
var filelist = new Array();
updateList = function () {
var input = document.getElementById('fileUploader');
var output = document.getElementById('divFiles');
var HTML = "<table>";
for (var i = 0; i < input.files.length; ++i) {
filelist[i]=input.files.item(i).name;
HTML += "<tr><td>" + filelist[i] + "</td><td> <button ></button></td></tr>";
}
HTML += "</table>";
output.innerHTML += HTML;
}
</script>
Please try this.
table {
border-collapse: separate;
border-spacing: 0 3px;
width: 600px;
}
Try this
table
{
table-layout: fixed;
width: 300px;
}
td
{
border: 1px solid green;
word-wrap:break-word;
}
try jsfiddle
<style>
table {
border-collapse: separate;
border-spacing: 0 2px;
width: 600px;
table-layout: fixed;
}
tr:nth-child(1n) {
border: 2px solid;
background-color: #eceff1;
color: Black;
}
tr:nth-child(2n) {
border: 2px solid;
color: Black;
}
td {
padding-top: .5em;
padding-left: .5em;
padding-right: .5em;
padding-bottom: .5em;
}
input[type="file"] {
display: none;
}
.label1 {
padding: 3px;
background: #fff;
display: table;
color:black;
}
button {
background-image: url('../../Images/delete.ico');
background-size: cover;
padding-right:0px;
background-color: Transparent;
cursor: pointer;
border: none;
width: 30px;
height: 30px;
}
</style>
<script>
$(document).ready(function () {
$(document).on('click', "button", function (e) {
$(this).closest('tr').remove();
});
});
</script>
<script>
var filelist = new Array();
updateList = function () {
var input = document.getElementById('fileUploader');
var output = document.getElementById('divFiles');
var HTML = "<table>";
for (var i = 0; i < input.files.length; ++i) {
filelist[i]=input.files.item(i).name;
HTML += "<tr><td>" + filelist[i] + "</td><td><button ></button></td></tr>";
}
HTML += "</table>";
output.innerHTML += HTML;
}
</script>
In the above script the delete button is showing in fixed order but i want the file name to be aligned at left and delete button need to at right side corner.

Javascript counting adaptive table rows

I am trying to learn JavaScript; this is what I made for a test. My problem is that I want to count my table rows, but when I remove a table name it should adapt the table row numbers.
Is there someone who can tell me how I should or could do this? If you have a comment about my coding please give it as I want to learn as much as possible.
var count = 0;
var btn = document.getElementById("btn");
var table = document.getElementById("table");
var removeRowBtn = document.getElementById("removeRowBtn");
var tableNr = document.getElementById("tableNr");
// input fields Variable
var firstName = document.getElementsByName("firstName")[0];
var lastName = document.getElementsByName("lastName")[0];
var Age = document.getElementsByName("Age")[0];
var Country = document.getElementsByName("Country")[0];
var AgeCheck = document.myForm.Age.valueOf;
// this function is checking if the input fields have the recuired data in it other wise it give's a error.
function validate() {
// first name field check + error
if( document.myForm.firstName.value == "" ) {
alert( "Please provide your first name!" );
document.myForm.firstName.focus() ;
return false;
}
// last name field check + error message
if( document.myForm.lastName.value == "" ) {
alert( "Please provide your last name!" );
document.myForm.lastName.focus() ;
return false;
}
// age field check + error message
if( isNaN(document.myForm.Age.value) || document.myForm.Age.value < 1 || document.myForm.Age.value > 100 ){
alert( "Please provide your age!");
return false;
}
// country select list check + error message
if( document.myForm.Country.value == "chooseCountry" ) {
alert( "Please provide your country!" );
return false;
}
// if evry thing is true return a value of true
return true;
}
function tableFunction() {
// if validate is true go
if( validate() ){
// count to see how many row's there are added
count++;
// making a new Row
var newRow = document.createElement("tr");
// adding the tow to the Table
table.appendChild(newRow);
// adding a class and a count-id to the Row
newRow.className = "tableRow";
newRow.setAttribute ("id", count);
// adding 4 td to the tr
for(i = 0; i < 5; i++ ){
var newData = document.createElement("td");
newRow.appendChild(newData);
newData.className = "tableData";
// check the td count and place data in.
if(i == 0){
table.getElementsByTagName("tr")[count].getElementsByTagName("td")[i].innerHTML = count;
} else if (i == 1) {
table.getElementsByTagName("tr")[count].getElementsByTagName("td")[i].innerHTML = firstName.value;
} else if (i == 2) {
table.getElementsByTagName("tr")[count].getElementsByTagName("td")[i].innerHTML = lastName.value;
} else if (i == 3) {
table.getElementsByTagName("tr")[count].getElementsByTagName("td")[i].innerHTML = Age.value;
} else if (i == 4){
table.getElementsByTagName("tr")[count].getElementsByTagName("td")[i].innerHTML = Country.value;
}
}
}
}
function removeTableRow(){
i = tableNr.value;
// if there is no table number filled in show a error alert
if( i == "" ) {
alert( "Please provide a table number!" );
tableNr.focus() ;
return false;
}
// find the chosen array
var row = table.getElementsByTagName("tr")[i];
// if the number is not in the row show error alert that it issen't in the table
if( row == undefined ){
alert( "this row number is not in the table" );
return false;
}
row.remove(row.selectedIndex);
}
removeRowBtn.onclick = function() {removeTableRow()};
btn.onclick = function(){ tableFunction()};
body{
background: white;
}
img{
height: 100%;
display: block;
margin: 0 auto;
}
p{
text-align: center;
}
.container{
width: 100%;
max-width: 600px;
border-radius: 2px;
margin: 0 auto;
margin-top: 8vh;
background: lightgray;
box-shadow: 0px 4px 4px darkgray;
}
table{
width: 100%;
text-align: center;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
/* Button */
.btn {
display: inline-block;
margin: 1em auto;
font-weight: 100;
padding: 1em 1.25em;
text-align: center;
width: 100% ;
border-radius: 1px;
position: relative;
z-index: 0;
cursor: pointer;
border: none;
background: #0c84e4;
box-shadow: 0px 1px 1px #063e6b;
color: #FFFFFF;
}
:focus {
outline: -webkit-focus-ring-color auto 0px;
}
.btn.red{
background:red;
width: 100%;
}
/* input field style's */
input[type=text] {
width: calc(25% - 8px);
padding: 12px 20px 12px 5px;
margin: 8px 4px;
box-sizing: border-box;
float: left;
border: none;
border-bottom: 2px solid #536DFE;
text-align: center;
background: transparent;
}
input:focus{
outline: none;
color: black;
}
::-webkit-input-placeholder{
color:black;
font: helvetica 12px bold ;
text-align: center;
}
select{
width: calc(25% - 8px);
padding: 12px 20px 12px 5px;
margin: 8px 4px;
box-sizing: border-box;
float: left;
border: none;
border-bottom: 2px solid #536DFE;
text-align: center;
background: transparent;
height: 39px;
border-radius: 0px !important;
}
<!DOCTYPE html>
<html>
<head>
<title>Inzend Opgave H5</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<!-- style sheets -->
<link href="style.css" rel="stylesheet" type="text/css" >
</head>
<body>
<div id="wrapper">
<section class="container">
<form id="personInfo" name="myForm">
<table>
<tbody id="table">
<tr>
<td>nr.</td>
<td>First Name</td>
<td>Last Name</td>
<td>Age</td>
<td>Country</td>
</tr>
</tbody>
</table>
<input type="text" name="firstName" placeholder="firstName">
<input type="text" name="lastName" placeholder="lastName">
<input type="text" name="Age" placeholder="Age">
<select name="Country">
<option value="choose a country">Kies een land</option>
<option value="Nederland">NL</option>
<option value="Belgie">BE</option>
<option value="Duitsland">DE</option>
</select>
<input type="button" name="button" id="btn" class="btn" value="Add the input fields to the table">
<p>To remove a table number fill in the input field with the <br> number of the table and click remove table row</p>
<input type="button" name="button" id="removeRowBtn" class="btn" value="remove table row" style="width: 75%;">
<input type="text" name="TableNr" id="tableNr" placeholder="table nr.">
</form>
</section>
</div>
<!-- java-scripts -->
<script type="text/javascript" src="script.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.2.js"></script>
<script type="text/javascript">
var cw = $('.container').width();
$('.container').css({
'height': cw + 'px'
});
</script>
</body>
</html>
Change
row.remove(row.selectedIndex);
to
row.remove(row.selectedIndex);
var rows = document.querySelectorAll("#table tr");
for (var i = 1; i < rows.length; i++) { rows[i].cells[0].innerText = i; }

Categories