How to get input text from table data - javascript

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();
});

Related

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
};

Store form data in Local Storage and display in table

How to store form input data? How to get it back and take actions like update, delete and clear?
Storing data using localStorage.setItem();
Getting data using localStorage.getItem();
I am taking user input and trying to save locally using JSON. Want to get data using JSON parse save it in table form. Want to take some actions like ADD Data, DELETE data on click. Clear the table using clear data () function. So I have related functions.
I am new. Didn't understand the logic completely.
HTML FORM:
<form id="form">
<label for="fname">First name:
<input type="text" id="fname" name="fname" placeholder
="name">
</label><br>
<label for="lname">Last name:
<input type="text" id="lname" name="lname"><br>
</label><br>
<button class="btn">Add</button>
<button class="btn">Clear List</button>
</form>
<table id="myTable">
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th> Action</th>
</tr>
<tableBody id="tabledata">
<tr>
<td>cc </td>
<td> qq </td>
<td><button class="btn">Delete</button></td>
</tr>
</tableBody>
</table>
SCRIPT:
let myfName = document.getElementById("fName").value;
let mylName = document.getElementById("lName").value;
if(localStorage.getItem('itemJson') == null){
itemJsonArray =[];
itemJsonArray
.push([ myfName, mylName]);
localStorage.setItem('itemJeson',
JSON.stringify(itemJsonArray))
}
else{
itemJsonArrayStr
localStorage.getItem('itemJeson');
itemJsonArry = JSON.parse(
itemJsonArrayStr);
itemJsonArray
.push([ myfName, mylName]);
localStorage.setItem('itemJeson',
JSON.stringify(itemJsonArray))
}
update();
// updating inputs in table
function update(){
if(localStorage.getItem('itemJson') == null){
itemJsonArray =[];
localStorage.setItem('itemJeson',
JSON.stringify(itemJsonArray))
}
else{
itemJsonArrayStr =
localStorage.getItem('itemJeson');
itemJsonArry = JSON.parse(
itemJsonArrayStr);
}
let tableData document.getElementById("tabledata");
let str = "";
itemJsonArray.forEach((element, index) => {
str += ` <tr>
<th scope="row"> ${index}</th>
<td> ${element[0]}</td>
<td> ${element [1]}</td>
<td><button class="btn btn-warning btn-sm" onclick = "deleted(${index}" >Delete</button></td>
</tr>`;
});
tablebody.innerHTML = str;
}
let add = document.getElementById("addItem");
add.addEventListener("click", getAndUpdate);
update();
<!DOCTYPE html>
<html>
<body>
<style>
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
</style>
<div id="result"></div>
<input id="data"></input>
<input type="date" id="date" name="date" value="2018-07-22" min="2018-01-01" max="2018-12-31">
<button onclick="Submit()">Submit</button>
<button onclick="Clear()">Clear</button>
<br><br><br><br><br>
<table id="table">
<tr>
<th>SL. NO</th>
<th>Task Name</th>
<th>Date</th>
</tr>
<tr id ="tbl_data">
</tr>
<tr>
</table>
<script>
// Check browser support
var taskData = [];
var i = null;
function Submit(){
if(taskData.length > 0){
var data = document.getElementById('data').value;
var date = document.getElementById('date').value;
const obj = { "data": data , "date": date}
var stored = JSON.parse(localStorage.getItem("task"));
stored.push(obj);
}
var data = document.getElementById('data').value;
var date = document.getElementById('date').value;
const obj = { "data": data , "date": date}
taskData.push(obj);
localStorage.setItem("task", JSON.stringify(taskData));
document.getElementById("result").innerHTML = localStorage.getItem("task");
if(i==null){
i= 0;
}
for ( i = i; i < taskData.length; ++i) {
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
row.insertCell(0).innerHTML= i+1;
row.insertCell(1).innerHTML= taskData[i].data;
row.insertCell(2).innerHTML= taskData[i].date;
i=i;
}
}
// Retrieve
</script>
</body>
</html>

hide div if value is blank (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();
}

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 value of checkbox in table?

How can I get value of checkbox in table? I want use it for in this case in order get parameter. Now, please see html table:
<table id="div_func" class="table table-bordered" style="width: 100%">
<thead>
<tr>
<th>
<input type="checkbox" id="chk_all" /></th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr>
<td> <input type="checkbox" class="checkbox1" id="chk" name="check[]" value="D01" /></td>
<td>Banana </td>
</tr>
<tr>
<td> <input type="checkbox" class="checkbox1" id="chk" name="check[]" value="D02" /></td>
<td>Orange </td>
</tr>
<tr>
<td> <input type="checkbox" class="checkbox1" id="chk" name="check[]" value="D03" /></td>
<td>Apple </td>
</tr>
</tbody>
</table>
And this is my script , I use for get value in checkbox , then put parameter
function add_funcgroup() {
var func_group = [];
var chk_allow = "";
var table = document.getElementById("div_func");
for (var i = 0; i < table.rows.length; i++) {
if ($('#chk')[i].is(':checked')) {
chk_allow = "True";
}
else {
chk_allow = "False";
}
var group_func = {
GROUP_MOD_ID: id_temp,
FUNCTION_MOD_ID: $('#chk')[i].val(),
ALLOW: chk_allow
};
func_group[i] = group_func;
}
var func_group_temp = {
FUNC_MOD: func_group
};
var DTO = {
'func_group_temp': func_group_temp
};
$.ajax(
{
And it's not working.
What you have done is right, but you are not outputting it to the table!
var table = $("#div_func");
var value_check = "";
for (var i = 1; i < table.rows.length; i++) {
if ($('#chk')[i].is(':checked')) {
value_check += i + ": " + $('#chk')[i].val();
}
}
alert(value_check);
And you aren't appending it, instead saving!
Try to this
$('#div_func tbody tr input:checkbox').each(function() {
if (this.checked) {
//Do something
}
});.

Categories