hide div if value is blank (javascript) - javascript

I am working on a phonebook. In html I have a div #containerAgenda which won't show if there are no added contacts. However, I created the function to delete a row or multiple rows. So if I add and then delete all contacts, I want the div to hide. I am not sure how to set the value to blank or empty so that I can apply the rule .classList.remove in the deleteRow function(I added the way I tried to define the input value as empty). Would you give me any hints? Below is my code:
P.S. I am quite a beginner so I appreciate non-complicated solutions :)
<script>
var persoane =[];
function deseneazaTabel(){
str = "";
for (var i = 0; i < persoane.length; i++){
str += `<tr>
<td>${persoane[i].name}</td>
<td>${persoane[i].telefon}</td>
<td><span class="editButton" onclick="editeaza();">EDIT</span></td>
<td><span class="deleteButton" onclick="deleteRow(${i});">STERGE</span></td>
</tr>`;
}
document.querySelector("table tbody").innerHTML=str;
}
var pers = {};
function adaugaContact(form,event){
event.preventDefault();
var inputs = form.querySelectorAll("input[name]");
for (var i=0; i<inputs.length; i++){
var a = inputs[i].getAttribute("name");
var v = inputs[i].value;
pers[a] = v;
}
persoane.push(pers);
document.querySelector("#containerAgenda").classList.remove("hidden");
deseneazaTabel();
}
function deleteRow (idx){
persoane.splice(idx,1);
if(document.querySelectorAll("input[name]").value === ""){
document.querySelector("#containerAgenda").classList.add("hidden");
}
deseneazaTabel();
}
</script>
<body onload="deseneazaTabel();">
<h1>AGENDA</h1>
<form class="orangeText centerText" onsubmit="adaugaContact(this,event);">
<label for ="name">Nume</label>
<input type="text" name="name" id="name">
<label for="telefon">Telefon</label>
<input type="text" name="telefon" id="telefon">
<br/>
<input type="submit" class="btn" value="ADAUGA CONTACT">
</form>
<div id="containerAgenda" class="orangeText centerText hidden">
<table id="inputs">
<thead>
<tr>
<td>Nume</td>
<td>Telefon</td>
<td></td>
<td></td>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</body>
</html>

What you need is if
(persoane.length === 0) {
document.getElementById('containerAgenda').style.display = 'none';
} else {
document.getElementById('containerAgenda').style.display = 'block';
}
inside deseneazaTabel function
I also added deleteAll functionality which was missing from your question please check demo
var persoane = [];
function deseneazaTabel() {
if (persoane.length === 0) {
document.getElementById('containerAgenda').style.display = 'none';
} else {
document.getElementById('containerAgenda').style.display = 'block';
}
str = "";
for (var i = 0; i < persoane.length; i++) {
str += `<tr>
<td>${persoane[i].name}</td>
<td>${persoane[i].telefon}</td>
<td><span class="editButton" onclick="editeaza();">EDIT</span></td>
<td><span class="deleteButton" onclick="deleteRow(${i});">STERGE</span></td>
</tr>`;
}
document.querySelector("table tbody").innerHTML = str;
}
function DeleteALL() {
persoane = [];
deseneazaTabel();
}
var pers = {};
function adaugaContact(form, event) {
event.preventDefault();
var inputs = form.querySelectorAll("input[name]");
for (var i = 0; i < inputs.length; i++) {
var a = inputs[i].getAttribute("name");
var v = inputs[i].value;
pers[a] = v;
}
persoane.push(pers);
document.querySelector("#containerAgenda").classList.remove("hidden");
deseneazaTabel();
}
function deleteRow(idx) {
persoane.splice(idx, 1);
if (document.querySelectorAll("input[name]").value === "") {
document.querySelector("#containerAgenda").classList.add("hidden");
}
deseneazaTabel();
}
<body onload="deseneazaTabel();">
<h1>AGENDA</h1>
<form class="orangeText centerText" onsubmit="adaugaContact(this,event);">
<label for="name">Nume</label>
<input type="text" name="name" id="name">
<label for="telefon">Telefon</label>
<input type="text" name="telefon" id="telefon">
<br/>
<input type="submit" class="btn" value="ADAUGA CONTACT">
</form>
<input type="submit" class="btn" onClick="DeleteALL()" value="Delete ALL">
<div id="containerAgenda" class="orangeText centerText hidden">
<table id="inputs">
<thead>
<tr>
<td>Nume</td>
<td>Telefon</td>
<td></td>
<td></td>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</body>
</html>

This can help you
function checkIfNoContact() {
if(document.querySelectorAll("tr").length <= 0 ) {
document.querySelector("#containerAgenda").classList.add("hidden");
} else {
document.querySelector("#containerAgenda").classList.remove("hidden");
}
}

You can Use jQuery
It will check if there wasn't any <tr> in <tbody>, then hides div#containerAgenda
I hope it works for you.
if ( $("#containerAgenda tbody").children().length == 0 ) {
$("#containerAgenda").hide();
}

Related

prevent added tables from disappearing when page is refreshed

basically, when user entered some values in each added rows, those values and the number of added rows don't disappear... how is that possible?
here's my code:
function delPlace(row) {
var txtb = document.getElementById('travel');
var len = txtb.rows.length;
if (len > 2) {
var i = row.parentNode.parentNode.rowIndex;
document.getElementById('travel').deleteRow(i);
} else {
alert("Can't delete all rows. One row must at least remain.");
}
}
function addPlace() {
var txtb = document.getElementById('travel');
var add_row = txtb.rows[1].cloneNode(true);
var len = txtb.rows.length;
add_row.cells[0].innerHTML = len;
var inp = add_row.cells[1].getElementsByTagName('input')[0];
inp.id += len;
inp.value = '';
txtb.appendChild(add_row);
}
<table id="travel">
<p> List the countries/cities the person had traveled to/from in the past 15 days before diagnosis </p>
<tr><input type="button" id="add_place" value="Add" onclick="addPlace()" /></tr>
<tr>
<td style="display:none"></td>
<td>
<input type="text" class="form-control" name="travel_history[]" value="" placeholder="Enter text here..."
style="width:500px">
</td>
<td>
<input type="button" id="del_place" value="Remove" onclick="delPlace(this)" />
</td>
</tr>
</table>
</div>

Reset the HTML table on change

I am working on expense management with pouchdb
The data is inserted into the database based on date
i want to reset to original table if there is no data in date onchange
Above picture is with data on particular date
if i change the date the table is not reset to original table
this picture is when changing the date the table is not resetting
only head row and one row is hard coded extra rows or dynamically created on click add row button
//add row
function addRow(no_of_rows){
for (let i = 0; i < no_of_rows; i++){
console.log(i)
var root = document.getElementById('customers').getElementsByTagName('tbody')[0];
var rows = root.getElementsByTagName('tr');
var clone = cloneEl(rows[rows.length - 1]);
cleanUpInputs(clone);
root.appendChild(clone);
function cloneEl(el) {
var clo = el.cloneNode(true);
return clo;
}
function cleanUpInputs(obj) {
for (var i = 0; n = obj.childNodes[i]; ++i) {
if (n.childNodes && n.tagName != 'INPUT') {
cleanUpInputs(n);
} else if (n.tagName == 'INPUT') {
n.value = '';
}
}
}
}
}
// getting data from pouchdb
function getAccounts(){
var getdate = document.getElementById('Expdate').value;
var table = document.getElementById('customers');
db.get(getdate, function(err, doc) {
if (err) {
//want to handle the table reset here
} else {
console.log(doc);
addRow(doc['DailyAccount'].length -1);
for (let i = 0; i < doc['DailyAccount'].length; i++){
// console.log(i);
table.rows[i+1].cells[0].firstChild.value = doc.DailyAccount[i]['Description'];
table.rows[i+1].cells[1].firstChild.value = doc.DailyAccount[i]['Investment'];
table.rows[i+1].cells[2].firstChild.value = doc.DailyAccount[i]['Expenses'];
}
document.getElementById("investtotal").value = doc.TotalInvestment;
document.getElementById("exptotal").value = doc.TotalExpenses;
}
});
}
<input type="date" name="Date" id="Expdate" onchange="getAccounts()" >
<button onclick="addRow(1)"><i class="fa fa-plus" aria-hidden="true"></i>Add Row</button>
<button onclick="DeleteRow()"><i class="fa fa-minus" aria-hidden="true"></i>Delete Row</button>
<table id="customers">
<tbody id="mytbody">
<tr>
<th>Descritption</th>
<th>Investment</th>
<th>Expenses</th>
</tr>
<tr>
<td><input type="text" name="yourname" /> </td>
<td onchange="getinvest()"><input type="number" name="yourname" /></td>
<td onchange="getexpense()"><input type="number" name="yourname" /></td>
</tr>
</tbody>
</table>
<label for="fname">Investment Total : </label>
<input type="number" name="Investtotal" id="investtotal">
<label for="fname">Expense Total : </label>
<input type="number" name="Exptotal" id="exptotal">
<input type="button" id="save" value ="save" name="save" onclick="day()">
structure of pouchdb doc
var Accountdoc = {
_id: getdate,
TotalInvestment:Totalinvest,
TotalExpenses: Totalexp,
DailyAccount: Accounts,// accounts is array of object
};

Javascript common function for multiple input type=text & input type=color

In my body tag i have two input types(text & color). It works like this,
If you give the hex value of color in the inputText, inputColor
will automatically change to that color.
If you select the color via colorPicker, inputText will
automatically change to the colorHex value you have chosen.
Below code works
<body>
<input type="text" id="txtColor">
<input type="color" id="colColor" >
<script>
document.getElementById("txtColor").onblur = function() {myFunction1()};
document.getElementById("colColor").onchange = function() {myFunction2()};
function myFunction1() {
//alert("Input field lost focus.");
var txtColor = document.getElementById("txtColor").value;
document.getElementById("txtColor").nextElementSibling.value = txtColor;
// document.getElementById("colColor").value = txtColor;
}
function myFunction2() {
//alert("Input field lost focus.");
var colColor = document.getElementById("colColor").value;
document.getElementById("colColor").previousElementSibling.value = colColor;
//document.getElementById("txtColor").value = colColor;
}
</script>
</body>
What i am trying to do is, i have a table with multiple rows of above pair(inputText & inputColor). It should function similarly to above. I am trying with getElementsByClassName having a common classname for inputText and inputColor, so that it would update the sibling with hexColor value or color.
This is my current code, its not working. Currently getting error "Uncaught TypeError: txtColorClass.addEventListener is not a function"
<body>
<table>
<tr>
<td>
<input type="text" id="txtColor0" class="txtColorClass">
<input type="color" id="colColor0" >
</td>
</tr>
<tr>
<td>
<input type="text" id="txtColor1" class="txtColorClass">
<input type="color" id="colColor1" >
</td>
</tr>
<tr>
<td>
<input type="text" id="txtColor2" class="txtColorClass">
<input type="color" id="colColor2" >
</td>
</tr>
</table>
<script>
var txtColorClass = document.getElementsByClassName("txtColorClass");
txtColorClass.addEventListener("blur", function( event ) {
//event.target.style.background = "pink";
var txtColor = event.target.value;
event.target.nextElementSibling.value = txtColor;
}, true);
//document.getElementById("txtColor").onblur = function() {myFunction1()};
document.getElementById("colColor").onchange = function() {myFunction2()};
function myFunction1() {
//alert("Input field lost focus.");
var txtColor = document.getElementById("txtColor").value;
document.getElementById("txtColor").nextElementSibling.value = txtColor;
// document.getElementById("colColor").value = txtColor;
}
function myFunction2() {
//alert("Input field lost focus.");
var colColor = document.getElementById("colColor").value;
document.getElementById("colColor").previousElementSibling.value = colColor;
//document.getElementById("txtColor").value = colColor;
}
</script>
</body>
Check below snippet
There are many possible way you can do this. Below is one of the possible way. And you can easily do this using jquery also.
var txtColorClass = document.getElementsByClassName("txtColorClass");
for(var i = 0; i < txtColorClass.length; i++)
{
txtColorClass.item(i).addEventListener("blur", function( event ) {
//event.target.style.background = "pink";
var txtColor = event.target.value;
event.target.nextElementSibling.value = txtColor;
}, true);
}
var colColorClass = document.getElementsByClassName("colColor");
function myFunction1() {
//alert("Input field lost focus.");
var txtColor = document.getElementById("txtColor").value;
document.getElementById("txtColor").nextElementSibling.value = txtColor;
// document.getElementById("colColor").value = txtColor;
}
function myFunction2(colColorBox) {
//alert("Input field lost focus.");
var colColor = colColorBox.value;
colColorBox.previousElementSibling.value = colColor;
//document.getElementById("txtColor").value = colColor;
}
<body>
<table>
<tr>
<td>
<input type="text" id="txtColor0" class="txtColorClass">
<input type="color" id="colColor0" class="colColor" onchange="myFunction2(this)">
</td>
</tr>
<tr>
<td>
<input type="text" id="txtColor1" class="txtColorClass">
<input type="color" id="colColor1" class="colColor" onchange="myFunction2(this)">
</td>
</tr>
<tr>
<td>
<input type="text" id="txtColor2" class="txtColorClass">
<input type="color" id="colColor2" class="colColor" onchange="myFunction2(this)">
</td>
</tr>
</table>
</body>
Thank You Very Much NewToJS with your hint i was able to resolve this.
<body>
<table>
<tr>
<td>
<input type="text" id="txtColor0" class="txtColorClass">
<input type="color" id="colColor0" class="colColorClass">
</td>
</tr>
<tr>
<td>
<input type="text" id="txtColor1" class="txtColorClass">
<input type="color" id="colColor1" class="colColorClass">
</td>
</tr>
<tr>
<td>
<input type="text" id="txtColor2" class="txtColorClass">
<input type="color" id="colColor2" class="colColorClass">
</td>
</tr>
</table>
<script>
var txtColorClass = document.getElementsByClassName("txtColorClass");
var colColorClass = document.getElementsByClassName("colColorClass");
for(let i = 0; i < txtColorClass.length; i++) {
txtColorClass[i].addEventListener("blur", function() {
var txtColor = event.target.value;
event.target.nextElementSibling.value = txtColor;
})
}
for(let i = 0; i < colColorClass.length; i++) {
colColorClass[i].addEventListener("change", function() {
var colColor = event.target.value;
event.target.previousElementSibling.value = colColor;
})
}
</script>
</body>

why my javascript code dosen't work(about search and filter bar)

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="utf-8">
<title>a1</title>
<link rel="stylesheet" href="a1.css" />
<script src="a1.js"></script>
</head>
<body>
<form id = "gallary" method="get" action="">
<div id="searchBox">
<input type="text" id="searchBar" placeholder="Search titles" />
<input type="submit" id="searchBtn" value="search" onclick="searchFunction()"/>
<select name="genre" id ="filterBar">
<option>Genre</option>
<option>Baroque</option>
<option>Mannerism</option>
<option>Neo-classicism</option>
<option>Realisim</option>
<option>Romanticism</option>
</select>
<input type="submit" id = "filterBtn" value="filter" onclick =
"filterFunction()" />
</div>
</form>
<div id="artistBox">
<table>
<caption>Paintings</caption>
<thead>
<tr>
<th></th>
<th>Title</th>
<th>Artist</th>
<th>Year</th>
<th>Genre</th>
</tr>
</thead>
<tbody id="tbody">
<tr>
<td><input type="checkbox" name="paintingname" /><img
src="05030.jpg"/></td>
<td>Death of Marat</td>
<td>David, Jacques-Louis</td>
<td>1793</td>
<td>Romanticism</td>
</tr>
<tr>
<td><input type="checkbox" name="paintingname" /><img
src="120010.jpg"/></td>
<td>Potrait of Eleanor of Toledo</td>
<td>Bronzino, Agnolo</td>
<td>1545</td>
<td>Mannerism</td>
</tr>
<tr>
<td><input type="checkbox" name="paintingname" /><img
src="07020.jpg"/></td>
<td>Liberty leading the people</td>
<td>Delacroix, Eugene</td>
<td>1830</td>
<td>Romanticism</td>
</tr>
<tr>
<td><input type="checkbox" name="paintingname" /><img
src="13030.jpg"/></td>
<td>Arrangement in Grey and Black</td>
<td>Whistler, James Abbott</td>
<td>1871</td>
<td>Realisim</td>
</tr>
<tr>
<td><input type="checkbox" name="paintingname" /><img
src="06010.jpg"/></td>
<td>Mademoiselle Caroline Riviere</td>
<td>Ingres, Jean-Auguste</td>
<td>1806</td>
<td>Neo-classicism</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
enter code here
above is my HTML code.
the searchBar is for searcing titles(the second column of tbody), the filter is for filtering genres(the fourth column of tbody).
I want to search and filter some specific content form the table and use on-click to trigger my functions but it didn't work. Can anyone help me?
var input = document.getElementById("searchBar").value.toUpperCase();
var tbody = document.getElementById("tbody");
var tr = tbody.getElementByTagName("tr");
var td;
var filter = document.getElementById("filterBar").value;
function makeGreen(inputDiv){
inputDiv.style.backgroundColor = "green";
}
function searchFunction(){
for (var i = 0; i < tr.length; i++) {
td = tr[i].getElementByTagName("td")[1];
if(td.innerHTML.toUpperCase() == input){
makeGreen(tr[i]);
}
};
}
function filterFunction(){
for (var i = 0; i < tr.length; i++) {
td = tr[i].getElementByTagName("td")[4];
if(td.innerHTML == input){
tr[i].style.display = "";
}else{
tr[i].style.display = "none";
}
}
You are setting the values of 'input', 'tbody','tr', and 'td' at the start of the script. These get evaluated when the script is loaded but destroyed when the the script file is finished loading. That is the "searchFunction" does not know about the values of these tags.
Consider the updated code: (see it in action at: Plunker)
<script type="text/javascript">
function makeGreen(inputDiv){
inputDiv.style.backgroundColor = "green";
}
function searchFunction(){
var input = document.getElementById("searchBar").value.toUpperCase();
var input = document.getElementById("searchBar").value.toUpperCase();
var tbody = document.getElementById("tbody");
var tr = tbody.getElementsByTagName("tr");
console.log(input);
for (var i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[1];
var filter = document.getElementById("filterBar").value;
if(td.innerHTML.toUpperCase() == input){
makeGreen(tr[i]);
}
};
}
function filterFunction(){
var input = document.getElementById("searchBar").value.toUpperCase();
var tbody = document.getElementById("tbody");
var tr = tbody.getElementsByTagName("tr");
for (var i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[4];
if(td.innerHTML == input){
tr[i].style.display = "";
}else{
tr[i].style.display = "none";
}
} // <-- Missing
}
</script>

How to get input text from table data

I made a table for the user input I've provided some textfield's so it can fill up the table. What I want to do I just want the user to fill up the table and let this save as pdf this will not create a records or insert in the database.
I just want totally save as pdf. But unfortunately when I <input type="text" class="form-control"> insert this in table data <td></td>. The value of the cell become this <input type="text" class="form-control">.
Table:
<div class = "col-md-12">
<table class = "table" id = "customFields">
<thead>
<tr>
<th>Stock No.</th>
<th>Unit</th>
<th class = "description">Description</th>
<th>Quantity</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" class="form-control"></td>
<td><input type="text" class="form-control"></td>
<td><input type="text" class="form-control"></td>
<td><input type="text" class="form-control"></td>
</tr>
</tbody>
</table>
<button type = "submit" class = "btn btn-primary" id = "addMore">+ Add</button>
<button type = "submit" class = "btn btn-danger" id = "removeRow">- Remove</button>
<button type = "submit" class = "btn btn-success" id = "downloadPDF">Download as PDF</button>
</div>
Script:
function tableToJson(table)
{
var data = [];
// first row needs to be headers
var headers = [];
for (var i=0; i<table.rows[0].cells.length; i++)
{
headers[i] = table.rows[0].cells[i].innerHTML.replace();
}
data.push(headers);
// go through cells
for (var i=1; i<table.rows.length; i++)
{
var tableRow = table.rows[i];
var rowData = {};
for (var j=0; j<tableRow.cells.length; j++)
{
rowData[ headers[j] ] = tableRow.cells[j].innerHTML;
}
data.push(rowData);
}
return data;
}
function genPDF()
{
//tableToJson is a special function which converts HTML object to Javascript Object Notation
var table = tableToJson($('#customFields').get(0));
//Defining pdf object
var doc = new jsPDF('1','pt','letter',true);
doc.cellInitialize();
$.each(table, function(i, row)
{
$.each(row, function(j, cell)
{
if(j == "#description" | j == 0)
{
doc.cell(1,10,190,20,cell,i);
}
else
{
doc.cell(1,10,90,20,cell,i);
}
});
});
doc.save('text.pdf');
}
$(document).ready(function ()
{
$("#downloadPDF").click(function ()
{
javascript:genPDF();
});
});
Sample JFiddle:
$(document).ready(function() {
$("#addMore").click(function() {
$("#customFields").append('<tr><td><input type="text" class="form-control"></td><td><input type="text" class="form-control"></td><td><input type="text" class="form-control"></td><td><input type="text" class="form-control"></td></tr>');
});
$("#removeRow").click(function() {
if ($('#customFields tbody tr').length == 1) {
} else {
$('#customFields tr:last').remove();
}
});
});
function tableToJson(table) {
var data = [];
// first row needs to be headers
var headers = [];
for (var i = 0; i < table.rows[0].cells.length; i++) {
headers[i] = table.rows[0].cells[i].innerHTML.replace();
}
data.push(headers);
// go through cells
for (var i = 1; i < table.rows.length; i++) {
var tableRow = table.rows[i];
var rowData = {};
for (var j = 0; j < tableRow.cells.length; j++) {
rowData[headers[j]] = tableRow.cells[j].innerHTML;
}
data.push(rowData);
}
return data;
}
function genPDF() {
//tableToJson is a special function which converts HTML object to Javascript Object Notation
var table = tableToJson($('#customFields').get(0));
//Defining pdf object
var doc = new jsPDF('1', 'pt', 'letter', true);
doc.cellInitialize();
$.each(table, function(i, row) {
$.each(row, function(j, cell) {
if (j == "#description" | j == 0) {
doc.cell(1, 10, 190, 20, cell, i);
} else {
doc.cell(1, 10, 90, 20, cell, i);
}
});
});
doc.save('text.pdf');
}
$(document).ready(function() {
$("#downloadPDF").click(function() {
javascript: genPDF();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.2.61/jspdf.debug.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.2.61/jspdf.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-12">
<table class="table" id="customFields">
<thead>
<tr>
<th>Stock No.</th>
<th>Unit</th>
<th class="description">Description</th>
<th>Quantity</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input type="text" class="form-control">
</td>
<td>
<input type="text" class="form-control">
</td>
<td>
<input type="text" class="form-control">
</td>
<td>
<input type="text" class="form-control">
</td>
</tr>
</tbody>
</table>
<button type="submit" class="btn btn-primary" id="addMore">+ Add</button>
<button type="submit" class="btn btn-danger" id="removeRow">- Remove</button>
<button type="submit" class="btn btn-success" id="downloadPDF">Download as PDF</button>
</div>
Cheers
Could loop through all the cells with <input> and replace those with their values before serializing the table to json
$('td:has(input)').text(function(){
return $(this).find('input').val();
});

Categories