Getting the values from textfield to save as PDF - javascript

I already can retrieve every values on my cell depending on what the user input. Using this.
$("#customFields > tbody tr > td").each(function()
{
console.log($(this).find("input").val());
});
But I'm just having a little problem on how can I append user input in the textfield? Becasue when I save as a pdf I got a crumpled <input type="text" class="form-control"> in one cell and it's not getting the values that I input. Screenshot below.
Screenshot:
Is there a way how can I input that values that I inserted here in every cell? I'm stuck in this part I need opinion from others how can I do this.
Table:
<div class = "col-md-12">
<table class = "table" id = "customFields">
<thead>
<tr>
<th>Stock No.</th>
<th>Unit</th>
<th>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-primary" id = "save">Save</button>
</div>
Script:
$("#customFields > tbody tr > td").each(function() {
console.log($(this).find("input").val());
});
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) {
doc.cell(1, 10, 90, 20, cell, i);
});
});
doc.save('text.pdf');
}
javascript: genPDF();

Replace your source code to:
for (var j = 0; j < tableRow.cells.length; j++) {
rowData[headers[j]] = tableRow.cells[j].children[0].value;
alert(rowData[headers[j]]);
}
This is my test
Hope this can help you. xD

Related

Dynamically Add and Remove Rows with Calculation Js

I would like a form where a user can add and remove rows.
Once the input has been added the respective fields will update by multiplying the qty * cost, as well as the bottom total field.
As I am new to js, I used the code from a pervious answer
However, the remove function is not working.
I have tried other solutions, however when a row gets removed the values don't update.
The ultimate goal is for a user to create a Quote with the tables and post it to a mysql database using ajax.
Therefore I changed the querySelectorAll to a class, for example class=qty, as more than one of the same id is not allowed.
Below is what I have so far.
The form:
<form name="add_name" id="add_service">
<table id="dataTable" class="form" border="1">
<tbody>
<tr id='row_0'>
<td>
<label>Service</label>
<input type="text" required="required"
name="service[]">
</td>
<td>
<label>Quantity</label>
<input type="text" class="qty" required="required"
name="qty[]" oninput="calculate('row_0')">
</td>
<td>
<label for="price">Price</label>
<input type="text" class="cost" required="required"
name="cost[]" oninput="calculate('row_0')">
</td>
<td>
<label for="total">Total</label>
<input type="text" class="subtotal"
required="required" name="subtotal[]">
</td>
<!--<td>
<a class="remove" href="#">Remove</a>
</td>-->
</tr>
</tbody>
</table>
<div>
<input type="text" class="" id="grand_total">
</div>
<input type="button" name="submit" id="submit" class="btn btn-
info" value="Submit"/>
</form>
<script>
$(document).ready(function () {
/**$('table').on('click', 'tr a.remove', function (e) {
e.preventDefault();
$(this).closest('tr').remove();
});*/
//submit data
$('#submit').click(function () {
$.ajax({
url: "push.php",
method: "POST",
data: $('#add_service').serialize(),
success: function (data) {
alert(data);
$('#add_service')[0].reset();
}
});
});
});
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
if (rowCount < 10) {
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
row.id = 'row_' + rowCount;
for (var i = 0; i < colCount; i++) {
var newcell = row.insertCell(i);
newcell.outerHTML = table.rows[0].cells[i].outerHTML;
}
var listitems = row.getElementsByTagName("input")
for (i = 0; i < listitems.length; i++) {
listitems[i].setAttribute("oninput", "calculate('" +
row.id + "')");
}
} else {
alert("Maximum 10.");
}
}
function calculate(elementID) {
var mainRow = document.getElementById(elementID);
var myBox1 = mainRow.querySelectorAll('[class=qty]')[0].value;
var myBox2 = mainRow.querySelectorAll('[class=cost]')[0].value;
var total = mainRow.querySelectorAll('[class=subtotal]')[0];
var myResult1 = myBox1 * myBox2;
total.value = myResult1;
grandtotal();
}
function grandtotal(){
//calculation script
var $form = $('#add_service'),
$sumDisplay = $('#grand_total');
var $summands = $form.find('.subtotal');
var sum = 0;
$summands.each(function ()
{
var value = Number($(this).val());
if (!isNaN(value)) sum += value;
});
$sumDisplay.val(sum);
}
</script>
From the question it is unclear how addRow is being called. I will assume that it is triggered by an event. You will need to uncomment the remove td and set the value of onclick:
<td>
<input type="button" class="remove" value="Remove" onclick="removeRow('dataTable', '0');">
</td>
and modify addRow as follows:
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
if (rowCount < 10) {
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
row.id = 'row_' + rowCount;
for (var i = 0; i < colCount; i++) {
var newcell = row.insertCell(i);
newcell.outerHTML = table.rows[0].cells[i].outerHTML;
}
var listitems = row.getElementsByTagName("input")
for (i = 0; i < listitems.length - 1; i++) {
listitems[i].setAttribute("oninput", "calculate('" +
row.id + "')");
}
listitems[listitems.length - 1].setAttribute("onclick", "removeRow('dataTable', " + row.id + ")");
} else {
alert("Maximum 10.");
}
}
This should result in your remove being generated. But we have a problem with ids, since if you remove the second row and there is a third row, then the way you specify the ids will result in duplicate ids. Therefore, if you remove an item, the ids of the subsequent rows will have to be decreased. Let's implement removeRow:
function removeRow(tableID, index) {
//Removing the row
var table = document.getElementById(tableID);
table.deleteRow(index);
//Modifying the ids of subsequent rows
var rowCount = table.rows.length;
for (var i = index; i < rowCount; i++) {
table.rows[i].id = "row_" + i;
}
//Handling the counts
grandtotal();
}
The code is untested, if you have any problem with it, I advise you to create a JSFiddle, so I will be able to easily test the code I have written.

Adding table rows and column dynamically with jQuery

I'm trying to add rows and columns to a table using user input values to determine the number of rows and columns dynamically using jQuery. Below is my code which actually adds rows and columns but not according to the user's inputs
function makeGrid() {
let numOfRow = 0; let numOfCol = 0;
$('#submit').on('click', function() {
numOfRow = $('#height').val();
numOfCol = $('#width').val();
for (var i = 1; i <= numOfRow; i++) {
let row = $('.grid-canvas').append('<tr>');
for (col = 1; col <= numOfCol; col++) {
$('tr').append('<td></td>');
}
}
});
}
makeGrid();
Assuming a user inputs numOfRow = 2 and numOfCol = 2, I should have a table like this
<tbody class="grid-canvas">
<tr>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
Problem is my code seems to be adding extra but I haven't been able to figure it out. This is the result of my code
<tbody class="grid-canvas">
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
</tbody>
How do I fix my code?
try changing your code from:
$('#submit').on('click', function() {
numOfRow = $('#height').val();
numOfCol = $('#width').val();
for (var i = 1; i <= numOfRow; i++) {
let row = $('.grid-canvas').append('<tr>');
for (col = 1; col <= numOfCol; col++) {
$('tr').append('<td></td>');
}
}
});
into this
$('#submit').on('click', function() {
numOfRow = $('#height').val();
numOfCol = $('#width').val();
var body = $('.grid-canvas');
for (var i = 1; i <= numOfRow; i++) {
let row = $('<tr></tr>');
for (col = 1; col <= numOfCol; col++) {
row.append('<td></td>');
}
body.append(row);
}
});
what i have done in the above code is created a separate object for the table's body and then once my rows are created with the columns, I append them back to the table object.
Pure javascript code is here
function f(x, y) {
var rows = x,
rowButtonNumber = y;
var table = document.getElementById("myTable");
table.innerHTML = "";
for (var i = 0; i < rows; i++) {
var tr = document.createElement("tr");
table.appendChild(tr);
for (var j = 0; j < rowButtonNumber; j++) {
var td = document.createElement("td");
var btn = document.createElement("button");
btn.innerHTML = "btn " + (i + 1);
btn.id = "btn-" + i;
btn.onclick = function() {
alert(this.innerHTML);
};
td.appendChild(btn);
tr.appendChild(td);
}
}
}
function go() {
var row = document.getElementById("row").value;
var col = document.getElementById("col").value;
f(row, col);
}
<html>
<head>
<style>
td {
width: 200px;
height: 200px;
}
button {
width: 100%;
height: 100%;
}
</style>
</head>
<body>
Rows
<input id="row" type="number" placeholder="Rows" />
<br> Columns
<input id="col" type="number" placeholder="Columns" />
<button onclick="go()">Go</button>
<table id="myTable" cellspacing="50">
</table>
</body>
It does not seem you are using the row variable. I would suggest appending newly created td to row instead of $('tr').

Changing html table row values indexes with pure Javascript

I have a scenarion where I delete rows in a html table. Once the row is deleted, I am trying to realign/sort the hidden fields indexes.
for example if second row with hidden fields name[1]abc tr is deleted, then I am trying to generate table with rows having hidden fields with index name[0] and name[1] etc., Any pointers ?
My fiddle
<table class="links-list">
<tbody>
<tr>
<td>test1</td>
<td>test2</td>
<input type="hidden" name="name[0]abc">
<input type="hidden" name="name[0]def">
<input type="hidden" name="name[0]gh1">
</tr>
<tr>
<td>test1</td>
<td>test2</td>
<input type="hidden" name="name[1]abc">
<input type="hidden" name="name[1]def">
<input type="hidden" name="name[1]gh1">
</tr>
<tr>
<td>test1</td>
<td>test2</td>
<input type="hidden" name="name[2]abc">
<input type="hidden" name="name[2]def">
<input type="hidden" name="name[2]gh1">
</tr>
</tbody>
</table>
Javascript
//Loop through table rows
//get all hidden fields for each row
// update index value inside name[index] in sorted order
// like all hidden fields with name[0] in first row name[1] for second row etc
function updateHyperlinkIndexes() {
var linksList = document.querySelector('.links-list tbody');
for (var i = 1; i < linksList.children.length; i++) {
var trContent = linksList.children[i];
for (var i = 0; i < trContent.children.length; i++) {
if (trContent.children.item(i).type && trContent.children.item(i).type === "hidden") {
var cellName = trContent.children.item(i).name;
trContent.children.item(i).name = cellName.replace(/[.*]/, i);
}
}
}
return linksList;
};
var updatedHtml = updateHyperlinkIndexes();
Found the problem, PFB working updateHyperlinkIndexes() function.
var linksList = document.querySelector('.links-list tbody');
for (var i = 0; i < linksList.children.length; i++) {
var trContent = linksList.children[i];
for (var j = 0; j < trContent.children.length; j++) {
console.log(trContent.children[j]);
if (trContent.children.item(j).type && trContent.children.item(j).type === "hidden") {
var cellName = trContent.children.item(j).name;
trContent.children.item(j).name = cellName.replace(/\[.*?\]/g, '['+i+']');
}
}
}
Changes made include correction of replace regex expression, it should be replace(/\[.*?\]/g, '['+i+']');. And secondly you used same variable i for iterating nested loops.
Hope it helps you.

Add table values to input field on button click

I have a DataTable that stores names only. I want to have a button that will add all the names in the DataTable to an text input field.
<div id="myTabDiv">
<table name="mytab" id="mytab1">
<thead>
<tr>
<th>name</th>
</tr>
</thead>
<tbody>
<tr>
<td>chris</td>
</tr>
<tr>
<td>mike</td>
</tr>
</tbody>
</table>
<button id="add" >ADD</button>
<input type="text" id="text">
</div>
After click the "add" button, I want the names to appear in the text field separated by a comma.
And if possible, If the button is clicked again, remove the names?
I created the whole solution on codepen. This is the function used:
var clicks = 0;
function csv() {
var box = document.getElementsByName('text')[0];
if(clicks === 0){
var newcsv = "";
var tds = document.getElementsByTagName("TD");
for(var i = 0; i < tds.length; i++)
{
newcsv += tds[i].innerHTML;
if(i != tds.length-1) newcsv += ",";
}
box.value = newcsv;
clicks++;
}
else{
clicks = 0;
box.value = "";
}
}
This is bound to onclick event of a button.
Assign id to input
<input type=text id="textbox"/>
Just loop though table
var table = document.getElementById("mytab1");
var textbox=document.getElementById("textbox")
for (var i = 0, row; row = table.rows[i]; i++) {
for (var j = 0, col; col = row.cells[j]; j++) {
if(textbox.value=="")
{
textbox.value=row.cells[j].innerText;
}
else
{
textbox.value+= textbox.value+','+row.cells[j].innerText;
}
}
}

Dynamically add new table row in Javascript

I used normal addRow function and removeRow function to dynamically add and remove the row in a table.
function addRow()
{
var ptable = document.getElementById('ptableQuestion');
var lastElement = ptable.rows.length;
var index = lastElement;
var row = ptable.insertRow(lastElement);
var cellLeft = row.insertCell(0);
var textNode = document.createTextNode(index);
cellLeft.appendChild(textNode);
var cellText = row.insertCell(1);
var element = document.createElement('textarea');
element.name = 'question' + index;
element.id = 'question' + index;
element.rows="2";
element.cols="60"
var cellText1 = row.insertCell(2);
var element1 = document.createElement('input');
element1.type = 'checkbox';
element1.name = 'cb';
element1.id = 'cb';
cellText.appendChild(element);
cellText1.appendChild(element1);
document.getElementById("psize").value=index;
}
function checkCheckboxes() {
var e = document.getElementsByName("cb");
var message = 'Are you sure you want to delete?';
var row_list = {length: 0};
for (var i = 0; i < e.length; i++) {
var c_box = e[i];
if (c_box.checked == true) {
row_list.length++;
row_list[i] = {};
row_list[i].row = c_box.parentNode.parentNode;
row_list[i].tb = row_list[i].row.parentNode;
}
}
if (row_list.length > 0 && window.confirm(message)) {
for (i in row_list) {
if (i == 'length') {
continue;
}
var r = row_list[i];
r.tb.removeChild(r.row);
}
} else if (row_list.length == 0) {
alert('You must select an email address to delete');
}
}
<form action="show.jsp" method="post" onsubmit="return validate();">
<input type="hidden" name="psize" id="psize">
<table style="border:1px solid #000000;" bgcolor="#efefef"
id="ptablePerson" align="center">
<tr>
<th colspan="3">Add New Person</th>
</tr>
<tr>
<td>1</td>
<td><input type="text" name="person1" id="person1" size="30" />
<input type="button" value="Add" onclick="addRow();" /></td>
<td><input type="checkbox" id="cb" name="cb"/></td>
</tr>
</table>
<table align="center">
<tr>
<td><input type="button" value="Remove" onclick="checkCheckboxes();" />
<input type="Submit" value="Submit" /></td>
</tr>
</table>
</form>
</BODY>
</HTML>
My problem is when the table got 5 row, if i click checkbox to delete row 3 the index become 1 2 4 5. Is there any method can rearrange it to 1 2 3 4
This looks like simple delete element from the list. You have to get all the rows of the table, and shift all rows one step backword after delete operation is completed.
There is a small code i which i has created a spn in every td.So that I will replace the value in the iterartion. It will work if u deleted 3(1,2,3,4,5) then the content of span will be 1,2,3,4 .Jquery i am using here
var rowCount = $('#ptableQuestion tr').length;
if (rowCount != 0) {
i = 0;
$('#ptableQuestion tr').each(function(i) {
$(this).find("td .spn").html(i);
});
}
});
Hope it will work for you.

Categories