How to automatically breaks the page using jspdf - javascript

I have a option for the user to add more row based on user's choice. If I add a row more than 9 or 10 the page breaks and the last row became half. I have 3 buttons Add, Remove and Save.
Add - to add more row.
Remove - to reduce row.
Save - to save as pdf.
This is my script where I adding and removing row happens.
Script: Add and Remove row.
$(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)
{
alert('Error');
}
else
{
$('#customFields tr:last').remove();
}
});
});
Script: Save as pdf.
$("#save").click(function ()
{
var values = "";
//i is the iterator and c is the control. So every elements iterates through the second input of callback function in this case the c variable. c is literally this current element in the array/
$.each($(".form-control"), function(i, c)
{
values = values + $(c).val().trim(); // .trim() to remove white-space
});
if(values.length > 0)
{
html2canvas(document.getElementById("captureMyDiv"),
{
onrendered: function(canvas)
{
var img = canvas.toDataURL("image/png");
var doc = new jsPDF();
doc.addImage(img, 'JPEG',0,0);
doc.save('text.pdf');
}
});
}
else
{
alert('Cannot be left blank');
}
});
HTML:
<div class = "col-md-8" id = "captureMyDiv">
<div class="jumbotron text-center">
<h2 style = "text-align: center">REQUISITION AND ISSUE SLIP</h2>
<h4 style = "text-align: center">NATIONAL LABOR RELATIONS COMMISSION</h4>
</div>
<form class = "form-vertical">
<div class = "form-group">
<label class = "control-label">Department:</label>
<input type = "text" class = "form-control">
</div>
<div class = "form-group">
<label class = "control-label">Office:</label>
<input type = "text" class = "form-control">
</div>
<div class = "form-group">
<label class = "control-label">Responsibility Center Code:</label>
<input type = "text" class = "form-control">
</div>
<div class = "form-group">
<label class = "control-label">RIS No:</label>
<input type = "text" class = "form-control">
</div>
<div class = "form-group">
<label class = "control-label">SAI No:</label>
<input type = "text" class = "form-control">
</div>
</form>
<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-success" id = "save">Save</button>
</div>
Screenshot:

Use a combination of css propertyes to brake the elements on the page like
page-break-after,page-break-before,page-break-inside
for more info

Related

I want to disable the selected Item from a Drop Down list for the next row's DropDown Dynamically

The HTML for the form is :
<form id="flowform" class="form" role="form" autocomplete="off">
<table id="add-flow-level" class="table table-striped table-borderless" style="width: 100%">
<thead>
<tr>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td>
<div class="col-sm-4">
<label class="required ">Min Amount</label>
<input type="text"
id="minAmount" name="minAmount" class="form-control min"
style="border-radius: 1rem; width: 183px;"
maxlength="100" required="required"
/>
<!-- onfocus = "maxAmountCheck(this.id);" -->
</div>
</td>
<td>
<div class="col-sm-4">
<label class="required ">Max Amount</label>
<input
type="text" id="maxAmount" name="maxAmount"
class="form-control max"
style="border-radius: 1rem; width: 183px;"
maxlength="100" required="required" />
<!-- onfocus = "maxAmountCheck(this.id);"/ -->
</div>
</td>
<td>
<div class="col-sm-4">
<label class="required">Approver</label>
<select class="form-control" id="approver" name="approver"
style="border-radius: 1rem; width: 183px;"
required="required" >
<!-- onfocus = "approverCheck(this.id);" -->
<option th:value="0">Select User</option>
<option th:each="usersList : ${usersList}"
th:value="${usersList.id}"
th:utext="${usersList.firstName +' '+ usersList.lastName}" />
</select>
</div>
</td>
<td>
<a href="#" id="addFlowLevelRow" class="btn btn-primary btn-label-left addFlowLevelRow" title="Add Next" style="margin-top: 18px;">
<i class="fa fa-plus" aria-hidden="true"></i>
</a>
</td>
</tr>
</tbody>
</table>
<br>
<div class="row">
<label class="control-label col-sm-5" style="margin-top: 8px;"></label>
<div class="col-sm-2">
<input type="submit" class="btn btn-primary btn-label-left"
value="Save" id="submitbtnflow" name="submitbtnflow"
style="border-radius: 1rem;">
</div>
<p id="msg" style="color: green;"></p>
</div>
</form>
js file
var countOfRows =1;
$(".addFlowLevelRow").click(function() {
var remv = "<a href='#' id='removeFlowLevelRow' class='btn btn-primary btn-label-left removeFlowLevelRow' title='Remove Row' style='margin-top: 33px;'><i class='fa fa-minus' aria-hidden='true'></i></a>";
var txt = $(this).closest("tr").find('#removeFlowLevelRow').attr('href');
if (txt == undefined && countOfRows < 5) {
var newRow = $(this).closest("tr").clone(true).appendTo("#add-flow-level").append(remv);
if(countOfRows == 4)
{
document.getElementsByClassName("addFlowLevelRow")[4].style.display = "none";
console.log("Removal of - button at row = "+countOfRows);
}
countOfRows++;
console.log("Number of row = "+countOfRows);
}
else if(countOfRows < 5){
var newRow = $(this).closest("tr").clone(true).appendTo("#add-flow-level");
if(countOfRows == 4)
{
document.getElementsByClassName("addFlowLevelRow")[4].style.display = "none";
console.log("Removal of - button at row = "+countOfRows);
}
countOfRows++;
console.log("Number of row =" +countOfRows);
}
var input = document.getElementsByClassName('max');
newRow.find('.min').val(input.value);
newRow.find('.max').val("");
newRow.find('#approver').val(0);
});
$(document).on('click', '#removeFlowLevelRow', function(e) {
console.log("view----");
$(this).closest("tr").remove();
countOfRows--;
console.log("After - Button count is = "+countOfRows);
});
$('#approver').on('change', function() {
alert("alerrt called");
var select = document.getElementById('approver');
var value = select.options[select.selectedIndex].value;
alert(value);
var index = value;
if (index > -1) {
// ${usersList}.splice(index, 1);
}
alert("ye ky tha"+select.value);
//return ${usersList};
});
I want that Super Admin to be disabled for the 2nd row and show values other than super Admin in that drop down.
Whenever the user clicks on + button it creates a clone of the row.
I have not created the new row separately but I want the new drop down to not have the value that are selected in the first drop down and this should go till 5 rows.
id's in the DOM should always be unique otherwise it can lead to strange behaviour in the page
so firstly you need to give each row's "approver" select element a separate id e.g. approver0,1,2... (or just remove the id) and instead have a common class for these elements e.g. "form-control approver"
Then in your onchange function, loop through the approver class and disable the select options that don't appear, here is some psuedo code to start working with
var a = document.getElementsByClassName("approver")
//loop through all approver select elements
for(i in a) {
if(a[i] = this) {
//do nothing if we loop to the element that has just been changed
}
else {
//if the approver select isn't the one we've just changed, loop through the options
options = a[i].childNodes
for(j in options){
if(options[j].value = this.value) {
//if the option matches the one we've just selected disable it
options[j].setAttribute("disabled")="disabled"
}
else {
//Otherwise re-enable it so we don't disable all elements by changing the selection
options[j].removeAttribute("disabled")
}
}
In this rudimentary example changing the next approver option will overwrite disabling the previous selection so you may need to also keep track of what has been selected in all other drop downs. but hopefully this gets you started

Change text input value based on check box, multiple fields with same class name

I have many checkboxes with same class name and below each there is a hidden date field.
I need to show the div with the date field and select different date.
in the begging I need to add 30 days from today when the checkbox is checked by default, then the user can change the date.
When I click to first choice and change the date is ok....but when I click to another the first date field takes the default value. Any suggestions?
html
#foreach (var item in Model)
{
<tr>
<td>
<div>
#Html.CheckBox(item.Title, new { #class = "chkPages", Value = item.ID }) #item.Title
</div>
<div class="extrafields">
<div class="DurationDisplayDate">
<input name="DurationDisplayDate" class="DurationDisplayDate" />
</div>
</div>
</td>
</tr>
-----------------------------
$('.chkPages').change(function () {
if (this.checked)
{
var dateStr = new Date();
dateStr.setDate(dateStr.getDate() + 30)
dateStr = dateStr.getDate() + "/" + (dateStr.getMonth() + 1) + "/" +
dateStr.getFullYear();
$(this).closest('div').next('.extrafields').fadeIn('slow');
//How can I change the next input field?
$(".DurationDate").val(dateStr);
}
else {
dateStr = "";
$(this).closest('div').next('.extrafields').fadeOut('slow');
$(".DurationDate").val(dateStr);
}
The main problems here are:
You are using "DurationDate" when the class is called "DurationDisplayDate"
You are selecting all elements with that class instead of just the relevant one in that row
An easy solution to this is to reuse the code you already have that's selecting the extras container for animation to find the relevant input e.g.
const extras = $(this).closest('div').next('.extrafields')
extras.find('.DurationDisplayDate').val(dateStr)
extras.fadeIn('slow')
Full working example:
$(document).ready(function() {
$('.chkPages').change(function() {
if (this.checked) {
var dateStr = new Date()
dateStr.setDate(dateStr.getDate() + 30)
dateStr = `${dateStr.getDate()}/${dateStr.getMonth() + 1}/${dateStr.getFullYear()}`
const extras = $(this).closest('div').next('.extrafields')
extras.find('.DurationDisplayDate').val(dateStr)
extras.fadeIn('slow')
} else {
const extras = $(this).closest('div').next('.extrafields')
extras.find('.DurationDisplayDate').val('')
extras.fadeOut('slow')
}
})
})
.extrafields {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td>
<div>
<input type="checkbox" class="chkPages" />
</div>
<div class="extrafields">
<div class="DurationDisplayDate">
<input name="DurationDisplayDate" class="DurationDisplayDate" />
</div>
</div>
</td>
</tr>
<tr>
<td>
<div>
<input type="checkbox" class="chkPages" />
</div>
<div class="extrafields">
<div class="DurationDisplayDate">
<input name="DurationDisplayDate" class="DurationDisplayDate" />
</div>
</div>
</td>
</tr>
<tr>
<td>
<div>
<input type="checkbox" class="chkPages" />
</div>
<div class="extrafields">
<div class="DurationDisplayDate">
<input name="DurationDisplayDate" class="DurationDisplayDate" />
</div>
</div>
</td>
</tr>
</table>

How to get the average of all the dynamic inputs

I can't find the average of all the inputs. My code only reads the input that i stated in html, but doesn't read the other dynamic ones.
Heres my code:
$(document).ready(function(){
// adds a new row
$(".addCF").click(function(){
$("#customFields").append('<tr valign="top"><th scope="row"><label for="customFieldName">Custom Field</label></th><td><input type="text" class="code" id="customFieldName" name="customFieldName[]" value="" placeholder="Input Name" /> Add Remove</td></tr>');
});
// deletes the row
$("#customFields").on('click','.remCF',function(){
$(this).parent().parent().remove();
});
$("#customFields").on('click','.add',function(){
$("#customFields").append('<tr valign="top"><th scope="row"><label for="customFieldName">Custom Field</label></th><td><input type="text" class="code" id="customFieldName" name="customFieldName[]" value="" placeholder="Input Name" /> Add Remove</td></tr>');
});
$("#click").click(function(){
var isbn = document.getElementById('customFieldName').value;
alert(isbn / $("input").length)
$("#averageGrade").text("Average Grade: " + isbn)
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="form-table" id="customFields">
<tr valign="top">
<th scope="row"><label for="customFieldName">Custom Field</label></th>
<td>
<input type="text" class="code" id="customFieldName" name="customFieldName[]" placeholder="Input Name" />
Add
</td>
</tr>
</table>
<button id = "click" class = "btn btn-primary" >Hi</button>
<p id = "averageGrade">Average Grade:</p>
Please help!
Thanks!
Each element.id must be unique - please change customFieldName to a class, and then iterate over the inputs and calculate the average. Also, you can reuse the same class for all "add" buttons and save that string in a variable so you don't have to paste it multiple times.
let inputTemplate = '<tr valign="top"><th scope="row"><label>Custom Field</label></th><td><input type="text" class="customFieldName code" name="customFieldName[]" value="" placeholder="Input Name" /> Add Remove</td></tr>';
$(document).ready(function() {
// adds a new row
$("#customFields").on('click', '.addCF', function() {
$("#customFields").append(inputTemplate);
});
// deletes the row
$("#customFields").on('click', '.remCF', function() {
$(this).parent().parent().remove();
});
$("#click").click(function() {
let fields = $('.customFieldName'),
total = 0;
for (let field of fields)
total += Number(field.value);
let average = total / fields.length;
$("#averageGrade").text("Average Grade: " + average);
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="form-table" id="customFields">
<tr valign="top">
<th scope="row"><label>Custom Field</label></th>
<td>
<input type="text" class="customFieldName code" name="customFieldName[]" placeholder="Input Name" />
Add
</td>
</tr>
</table>
<button id="click" class="btn btn-primary">Hi</button>
<p id="averageGrade">Average Grade:</p>
First of all, you need a way to select all the fields. Since id must (should) be unique, you could use the name or the class .code and remove id="customFieldName".
Then, getElementById, as its name suggests, returns one element. You need to select them all! If you're using class names, you can use getElementsByClassName, or querySelectorAll, or, since you're already using jQuery, just $(".code"), along with a loop to read each input's value (it you use jQuery, you can also use each()).
var sum=0,count=0,average;
$(".code").each(function() {
var value=parseInt($(this).val());
//You may want to validate the field
if(!isNaN(value)) sum+=value;
count++;
});
average=sum/count;
...
As many has pointed out (including myself in the comment section), you are going about using the wrong selector. id is a unique selector, meaning that the script will look at the first instance of the id and then stop immediately after.
What you need to do is use a selector that goes through every occurance of its instance. This is why class selectors exist. That will be the first fix in your code.
How I would go about calculating the average, personally, would be to make an array and push(); the values of the grades into the array. We will also need to do a parseInt() to make sure that our values are in fact handled as numbers. Otherwise, they'll be interpreted as strings.
You will then need to loop through the array, sum the values and divide by the length of the array.
HTML Example:
<div class="row">
<div class="col-12">
<table class="table form-table" id="customFields">
<tr valign="top">
<th scope="row"><label>Custom Field</label></th>
<td>
<input type="number" class="customFieldName" placeholder="Input Number" />
Add
</td>
</tr>
</table>
</div>
</div>
<div class="row">
<div class="col-md-4">
<button id="calcAvrgBtn" class="btn-primary">Calculate average grade</button>
</div>
<div class="col-md-4">
<p id="averageCalc"></p>
</div>
</div>
jQuery Example:
$('.addCF').on("click", function() {
$("#customFields").append('<tr valign="top"><th scope="row"><label>Custom Field</label></th><td><input type="number" class="customFieldName" placeholder="Input Number" /> Remove</td></tr>');
});
$(document).on("click", "a.remCF" , function() {
$(this).parent().parent().remove();
});
$('#calcAvrgBtn').on("click", function() {
let gradeArr = [];
$('.customFieldName').each(function() {
gradeArr.push(parseInt($(this).val()));
});
let total = 0;
for(var i = 0; i < gradeArr.length; i++) {
total += gradeArr[i];
}
let avg = total / gradeArr.length;
$('#averageCalc').text("The average grade is: "+avg);
});
Codepen example can be found here.
Snippet Example:
$('.addCF').on("click", function() {
$("#customFields").append('<tr valign="top"><th scope="row"><label>Custom Field</label></th><td><input type="number" class="customFieldName" placeholder="Input Number" /> Remove</td></tr>');
});
$(document).on("click", "a.remCF" , function() {
$(this).parent().parent().remove();
});
$('#calcAvrgBtn').on("click", function() {
let gradeArr = [];
$('.customFieldName').each(function() {
gradeArr.push(parseInt($(this).val()));
});
let total = 0;
for(var i = 0; i < gradeArr.length; i++) {
total += gradeArr[i];
}
let avg = total / gradeArr.length;
$('#averageCalc').text("The average grade is: "+avg);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet"/>
<div class="row">
<div class="col-12">
<table class="table form-table" id="customFields">
<tr valign="top">
<th scope="row"><label>Custom Field</label></th>
<td>
<input type="number" class="customFieldName" placeholder="Input Number" />
Add
</td>
</tr>
</table>
</div>
</div>
<div class="row">
<div class="col-md-4">
<button id="calcAvrgBtn" class="btn-primary">Calculate average grade</button>
</div>
<div class="col-md-4">
<p id="averageCalc"></p>
</div>
</div>

unable to get check boxes value from table

I am not able to get the checkboxes values from checkboxes to Firebase.
How will I be able to get each value from each box from each row?
Table:
Check boxes:
$("#table_body_Test").append("<tr><td>" + AgentEmail + "</td><td><INPUT TYPE=\"Checkbox\" Name=\"Browser\" Value =\"Agent\"></Input></td></tr>");
Table
<div class="AgentDetailsRequest">
<table id="testTable" align="center">
<thead>
<tr style="color: #D2002E; background: #FFCC01; height:32px;">
<td>Agents</td>
<td>Select</td>
</tr>
</thead>
<tbody id="table_body_Test">
</tbody>
</table>
</div>
full form
<div class="form-popup" id="myFormDetails">
<div class="shipDetailsRequest">
<form action="" method="post" class="form-container" >
<button type="button" onclick="closeForm()" id="close">x</button>
<input name="RR" type="RRField" id="date" disabled>
<input name="RR" type="RRField" id="RRField" placeholder="RR Field" disabled>
<p>Customer Details</p>
<input onclick="sampleFunction()" type="number1" placeholder="Customer Account Number" name="customerAccountField" id="customerAccountField" required>
<input type="number1" placeholder="Customer Name" name="customerNameField" id="customerNameField" disabled>
<p>Shipper Details</p>
<input type="number1" placeholder="Shipper Name" name="senderName" id="shipperName" required>
<textarea name="collectionAddress" placeholder="Collection Address...?" id="collectionAddress"></textarea>
<p>Shipment Details</p>
<input type="text" placeholder="Enter Origin" name="shptOrigin" id="shipmentOrigin" maxlength = "3" required>
<input type="text" placeholder="Enter Destination" name="shptDest" id="shipmentDest" maxlength = "3" required>
<input type="number" placeholder="Enter Weight" name="shptWeight" id="shptWeight" required>
<input type="number" placeholder="Enter Pieces" name="shptPieces" id="shptPieces" required>
<input type="number1" placeholder="Enter Dimensions" name="shptDimensions" id="shipmentDimensions" >
<select placeholder="Choose Type" name="shptStack" id="shptStack" required>
<option value="Stackable">Stackable</option>
<option value="Nonstackable">Nonstackable</option>
</select>
<select placeholder="Choose Desk" name="Desk" id="ChooseDesk" required>
<option value="KSA">KSA Desk</option>
<option value="DHA">DHA Desk</option>
<option value="RUH">RUH Desk</option>
<option value="JED">JED Desk</option>
</select>
<p>Comment</p>
<textarea name="comment" placeholder="Other Details...?" id="commentField"></textarea>
<div class="mainDiv" align="center" >
<input type="file" id="fileButton" />
<progress id="uploader" value="0" max="100" style="max-width: 128px;">0%</progress>
</div>
<!-- <button id="submitBtn" onclick="ActionData()">Next</button> -->
<button id="submitBtn" onclick="ActionData()">Next</button>
</form>
</div>
<div class="AgentDetailsRequest">
<table id="testTable" align="center">
<thead>
<tr style="color: #D2002E; background: #FFCC01; height:32px;">
<td>Agents</td>
<td>Select</td>
</tr>
</thead>
<tbody id="table_body_Test">
</tbody>
</table>
</div>
Full JavaScript
var DateText = document.getElementById("date");
var RRText = document.getElementById("RRField");
var CustAccText = document.getElementById("customerAccountField");
var CustNameText = document.getElementById("customerNameField");
var ShipperNameText = document.getElementById("shipperName");
var CollectionAddressText = document.getElementById("collectionAddress");
var ShipmentOrgText = document.getElementById("shipmentOrigin");
var ShipmentDestText = document.getElementById("shipmentDest");
var ShipmentweightText = document.getElementById("shptWeight");
var ShipmentPiecesText = document.getElementById("shptPieces");
var ShipmentDimensionsText = document.getElementById("shipmentDimensions");
var ShptStackText = document.getElementById("shptStack");
var ChooseDeskText = document.getElementById("ChooseDesk");
var CommentText = document.getElementById("commentField");
var ShipmentOriginValues = ShipmentOrgText.value;
ShipmentOriginValues = "All";
var uploader = document.getElementById('uploader');
var fileButton = document.getElementById('fileButton');
if (ShipmentOrgText.value != null)
{
var rootRefReAgents = firebase.database().ref().child("AgentsContact").child(ShipmentOriginValues);
rootRefReAgents.on("child_added", snap =>{
var AgentEmail = snap.child("Name").val();
$("#table_body_Test").append("<tr><td>" + AgentEmail + "</td><td><INPUT TYPE=\"Checkbox\" Name=\"Browser\" Value =\"Agent\"></Input></td></tr>");
});
}
function ActionData()
{
//setting up values from Text Fields
var DateValue = DateText.value;
var RRValue = RRText.value;
var CustAccountValue = CustAccText.value;
var CustNameValue = CustNameText.value;
var ShipperNameValue = ShipperNameText.value;
var CollectionAddressValues = CollectionAddressText.value;
ShipmentOriginValues = ShipmentOrgText.value;
var ShipmentDestValues = ShipmentDestText.value;
var ShipmentweightValues = ShipmentweightText.value;
var ShipmentPiecesValues = ShipmentPiecesText.value;
var ShipmentDimensionsValues = ShipmentDimensionsText.value;
var ShptStackValues = ShptStackText.value;
var ChooseDeskValues = ChooseDeskText.value;
var CommentValues = CommentText.value;
var FirebaseRef = firebase.database().ref("Requests").child(RRValue);
if(RRValue && ShipmentOriginValues && ShipmentDestValues && CustAccountValue == null)
{
window.alert("Need More details to upload")
}
else
{
FirebaseRef.child("Date").set(DateValue);
FirebaseRef.child("RR").set(RRValue);
FirebaseRef.child("Customer Account").set(CustAccountValue);
FirebaseRef.child("Customer Name").set(CustNameValue);
FirebaseRef.child("Shipper Name").set(ShipperNameValue);
FirebaseRef.child("Collection Address").set(CollectionAddressValues);
FirebaseRef.child("Origin").set(ShipmentOriginValues);
FirebaseRef.child("Destination").set(ShipmentDestValues);
FirebaseRef.child("Weight").set(ShipmentweightValues);
FirebaseRef.child("Pieces").set(ShipmentPiecesValues);
FirebaseRef.child("Dimensions").set(ShipmentDimensionsValues);
FirebaseRef.child("Stack").set(ShptStackValues);
FirebaseRef.child("Desk").set(ChooseDeskValues);
FirebaseRef.child("Comment").set(CommentValues);
FirebaseRef.child("Status").set("Pending");
//Uploading
fileButton.addEventListener('change', function(e){
var file = e.target.files[0];
var storageRef = firebase.storage().ref('img/'+RRValue+'/'+file.name);
var task = storageRef.put(file);
task.on('state_changed', function progress(snapshot) {
var percentage = (snapshot.bytesTransferred/snapshot.totalBytes)*100;
uploader.value = percentage;
}, function error(err) {
},function complete() {
});
});
}
}
I need to check boxes from the table and get their values back to Firebase when form is submitted.
You could specify an id or name for each input and then retrieve their value when you submit the form.
$("#table_body_Test").append("<tr><td>" + AgentEmail + "</td><td><input type=\"checkbox\" id=\""+AgentEmail+"\" Value =\"Agent\"></Input></td></tr>")
var agents = ... //Get your agents list from firebase
$form.on('submit', function(){
agents.forEach(function(agent){
if($('#'+agent.email).prop('checked'){
//do something
}
})
})
If your code is working, you can ckeck if a checkbox is checked with:
/* jQuery */
if ($('#check_id').is(":checked"))
{
// checkbox is checked
}
you can also use:
/* jQuery */
$("#idOfCurrentRow").children()."input[type='checkbox']") is(":checked")
If you prefer pure JavaScript:
/* pure JavaScript*/
if(document.getElementById("idOfYourCheckbox").checked) {
...
}
or
if (document.getElementByName("nameOfYourCheckbox").checked) {
.....
}

cost splitter javascript app

I am trying to make a cost splitter app for my roommates. I am explaining the app with an example. Suppose we are 4 members, there is a cost of 300, and 3 members (m1, m3, m4) participated in the expenditure (all have an equal share). Among them 2 members have paid the amount as follows: m3 paid 180 and m4 paid 120. Now the balance sheet will look like this:
m1(-100), m2(0), m3(+80), m4(+20)
I am not able to get all the form values properly and make the balance sheet.
<div>
<table id="dashboard">
<tr>
<th>TOTAL</th>
<th>member1</th>
<th>member2</th>
<th>member3</th>
<th>member4</th>
</tr>
<tr>
<td id="total"></td>
<td id="bmem1">0</td>
<td id="bmem2">0</td>
<td id="bmem3">0</td>
<td id="bmem4">0</td>
</tr>
</table>
</div>
<div id="newCostButton">
<button id="showForm" href="#">Add New Cost</button>
</div>
<form id="elForm">
<label>Cost:</label>
<input type="text" id="cost" placeholder="Add new cost">
<br>
<label><b>Participants:</b></label><br>
<span>member1</span>
<input type="checkbox" name="Participant" value="member1">
<span>member2</span>
<input type="checkbox" name="Participant" value="member2">
<span>member3</span>
<input type="checkbox" name="Participant" value="member3">
<span>member4</span>
<input type="checkbox" name="Participant" value="member4">
<br>
<b>contributors:</b><br>
member1
<input class= "contributors" type="text" name="member1">
member2
<input class= "contributors" type="text" name="member2">
member3
<input class= "contributors" type="text" name="member3">
member4
<input class= "contributors" type="text" name="member4">
<input type="submit" id="cal" value="calculate">
</form>
<div id="doc"></div>
<script>
$(function(){
var $newCostButton = $('#newCostButton');
var $elForm = $('#elForm');
var $cost = $('#cost');
$newCostButton.show();
$elForm.hide();
$newCostButton.on('click', function(){
$newCostButton.hide();
$elForm.show();
});
$('input:text').focus(function(){
$(this).val("");
});
function cal(){
var c = $cost.val();
var part = $('input:checked');
pCount = part.length;
var d= parseInt(c/pCount);
var contributors = $('.contributor');
var mem = [];
contributors.each(function(){
mem.push(parseInt($(this).val()));
});
console.log(mem);
for(var i=0;i<pCount;i++){
var r = mem[i]-d;
console.log(r);
}
}
$elForm.on('submit', function(e){
e.preventDefault();
cal();
});
</script>
I don't see where you import jquery
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
why don't you use excel or google sheets?
I think this does something similar to what you are asking for. I simplified a few things like .hide() and .show(), but they're easy enough to add back. Hopefully something in here helps. If not, it was still a fun hour code challenge.
html:
<div>
<table class="dashboard">
<tr>
<th>TOTAL</th>
<th>member1</th><th>member2</th><th>member3</th<th>member4</th>
</tr>
<tr>
<td>0</td><td>0</td><td>0</td><td>0</td><td>0</td>
</tr>
</table>
</div>
<div class="newCost">
<span>Cost:</span><input type="text" placeholder="Add New Cost">
<button>Add New Cost</button>
</div>
<div class="participants">
<p>Participants:</p>
<span>member1</span><input type="checkbox">
<span>member2</span><input type="checkbox">
<span>member3</span><input type="checkbox">
<span>member4</span><input type="checkbox">
</div>
<div class="contributors">
<p>Contributors:</p>
member1 <input type="text">
member2 <input type="text">
member3 <input type="text">
member4 <input type="text">
</div>
<button class="calculate">calculate</button>
javascript:
String.prototype.toInt = function() { return parseInt(this, 10); };
$('.newCost button').on('click', function() {
let newCost = $('.newCost input').val().toInt();
$('.dashboard td')
.each(function(index, td) {
td.textContent = td.textContent.toInt() + (index ? newCost / 4 : newCost);
});
});
$('button.calculate').on('click', function() {
$('.participants input').each(function(index){
if (this.checked) {
this.checked = false;
let currentOwed = $(`.dashboard td:eq(${index + 1})`).text().toInt();
let contributed = $(`.contributors input:eq(${index})`).val().toInt();
let total = $('.dashboard td:eq(0)').text().toInt();
$('.dashboard td:eq(0)').text(total -= contributed);
$(`.dashboard td:eq(${index + 1})`).text(currentOwed -= contributed);
}
});
});
$('button').click(()=> { $('input[type=text]').val(''); });
https://jsfiddle.net/wn7bbxjk/

Categories

Resources