calulate function in javascript for dynamically added field - javascript

I want to calculate subtotal and total for my form
i tried some javascripts but dident worked for me
some of them were only for static table since i am adding dynamic rows they were not helpfull
can any one help me to add script
formula
1) subtotal = amount1+ amount2+...+ amount(n)
2) total = total - discount
here are my codes
function calculateSubTotal()
{
var SubTotal = +amnt.value + +amnt.value;
document.getElementById("sub_total").value = isNaN(SubTotal) ? 0 : SubTotal;
}
document.getElementById("amnt").onchange = calculateSubTotal;
document.getElementById("amnt").onkeyup = calculateSubTotal;
function calculate(elm) {
var tr = elm;
while ((tr = tr.parentElement) && tr.tagName !== 'TR');
var inputs = tr.querySelectorAll('input,select');
var myBox1 = inputs[2].value;
var myBox2 = inputs[3].value;
var myResult = myBox1 * myBox2;
inputs[4].value = myResult;
}
var count = "1";
function addRow(in_tbl_name)
{
var tbody = document.getElementById(in_tbl_name).getElementsByTagName("TBODY")[0];
// create row
var row = document.createElement("TR");
// create table cell 1
var td1 = document.createElement("TD")
var strHtml1 = "<INPUT TYPE=\"text\" NAME=\"i_name[]\" PLACEHOLDER=\"Name\" SIZE=\"30\">";
td1.innerHTML = strHtml1.replace(/!count!/g,count);
// create table cell 2
var td2 = document.createElement("TD")
var strHtml2 = "<INPUT TYPE=\"text\" NAME=\"i_desc[]\" PLACEHOLDER=\"Description\" SIZE=\"30\">";
td2.innerHTML = strHtml2.replace(/!count!/g,count);
// create table cell 3
var td3 = document.createElement("TD")
var strHtml3 = "<INPUT TYPE=\"text\" NAME=\"i_qty[]\" PLACEHOLDER=\"QTY\" ID=\"qty\" ONINPUT=\"calculate(this)\" SIZE=\"30\">";
td3.innerHTML = strHtml3.replace(/!count!/g,count);
// create table cell 4
var td4 = document.createElement("TD")
var strHtml4 = "<INPUT TYPE=\"text\" NAME=\"i_rate[]\" PLACEHOLDER=\"Rate\" ID=\"rate\" ONINPUT=\"calculate(this)\" SIZE=\"30\">";
td4.innerHTML = strHtml4.replace(/!count!/g,count);
// create table cell 5
var td5 = document.createElement("TD")
var strHtml5 = "<INPUT TYPE=\"text\" NAME=\"i_amnt[]\" PLACEHOLDER=\"Amount\" ID=\"amnt\" >";
td5.innerHTML = strHtml5.replace(/!count!/g,count);
// create table cell 4
var td6 = document.createElement("TD")
var strHtml6 = "<INPUT TYPE=\"Button\" CLASS=\"Button\" onClick=\"delRow()\" VALUE=\"Delete Row\">";
td6.innerHTML = strHtml6.replace(/!count!/g,count);
// append data to row
row.appendChild(td1);
row.appendChild(td2);
row.appendChild(td3);
row.appendChild(td4);
row.appendChild(td5);
row.appendChild(td6);
// add to count variable
count = parseInt(count) + 1;
// append row to table
tbody.appendChild(row);
}
function delRow()
{
var current = window.event.srcElement;
//here we will delete the line
while ( (current = current.parentElement) && current.tagName !="TR");
current.parentElement.removeChild(current);
}
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post" >
<h3> Add New Purchase</h3>
<div class="vali-form">
<div class="col-md-3 form-group2 group-mail">
<select required name="s_account">
<option >--Select Account Name--</option>
<?php while ($row = mysqli_fetch_array($run)) {
echo '<option value="'.$row['acc_name'].'">'.$row['acc_name'].'</option>';}?>
</select>
</div>
<div class="clearfix"> </div>
<div class="col-md-4 form-group1 form-last">
<label class="control-label">Reminder</label>
<input type="text" name="s_rem" placeholder="" required="">
</div>
<div class="col-md-4 form-group1 group-mail">
<label class="control-label">Invoice Date</label>
<input type="date" name="s_idate" class="form-control1 ng-invalid ng-invalid-required" ng-model="model.date" placeholder="" required="">
</div>
<div class="col-md-4 form-group1 group-mail">
<label class="control-label ">Due Date</label>
<input type="date" name="s_ddate" class="form-control1 ng-invalid ng-invalid-required" ng-model="model.date" required="">
</div></div>
<div class="clearfix"> </div>
<div class="col-md-12 form-group1 form-last">
<div class="table-responsive">
<TABLE ID="tblPets" class="table table-striped table-bordered table-hover">
<tr>
<th><center>Item Name</center></th>
<th><center>Description</center></th>
<th><center>Qty.</center></th>
<th><center>Rate</center></th>
<th><center>Amount</center></th>
<th><center><INPUT TYPE="Button" onClick="addRow('tblPets')" VALUE="Add Row"></center></th>
</tr>
<tr>
<th><center><div class="col-md-12 form-group2 group-mail">
<select name="i_name[]">
<option >Select</option>
<?php while ($row1 = mysqli_fetch_array($run1)) {
echo '<option value="'.$row1['itm_name'].'">'.$row1['itm_name'].'</option>';}?>
</select>
<div></center></th>
<th><center><INPUT TYPE="text" NAME="i_desc[]" PLACEHOLDER="Description" SIZE="30"></center></th>
<th><center><INPUT TYPE="text" NAME="i_qty[]" PLACEHOLDER="QTY" ID="qty" ONINPUT="calculate(this)" SIZE="30"></center></th>
<th><center><INPUT TYPE="text" NAME="i_rate[]" PLACEHOLDER="Rate" ID="rate" ONINPUT="calculate(this)" SIZE="30"></center></th>
<th><center><INPUT TYPE="text" NAME="i_amnt[]" PLACEHOLDER="Amount" ID="amnt" ></center></th>
<th></th>
</tr>
</TABLE>
<div class="clearfix"> </div>
<div class="vali-form">
<div class="col-md-6 form-group1 form-last">
<label class="control-label">Subtotal</label>
<input type="text" name="s_stotal" placeholder="" required="">
</div>
<div class="col-md-6 form-group1 form-last">
<label class="control-label">Discount</label>
<input type="text" name="s_discount" placeholder="" required="">
</div>
<div class="col-md-6 form-group1 form-last">
<label class="control-label">Total</label>
<input type="text" name="s_total" placeholder="" required="">
</div>
<div class="col-md-6 form-group1 form-last">
<label class="control-label">Balance Due</label>
<input type="text" name="s_bald" placeholder="" required="">
</div>
<div class="clearfix"> </div>
</div>
<div class="col-md-12 form-group">
<button type="submit" name="Submit" class="btn btn-primary">Submit</button>
<button type="reset" class="btn btn-default">Reset</button>
</div>
<div class="clearfix"> </div>
</div>
</form>

If I understood you correctly, the code you are looking for should look something like this:
var values = document.querySelectorAll('input.amnt'),//find all inputs
//that you need to add
//use regular dom selector
//like in css
subtotal = 0;
for(var i = 0, ; = values.length; i<l; i++ ) {
subtotal += values[i].value;
}
It'll always add all the vales in the documents, you can add or remove data, doesn't matter.
PS please do not use <center> tag - it's deprecated, you should be using css for that.

A little something I put together after reading your issue. This still needs plenty of work doing to it but this should get you on the right lines.
I have added comments within the source code to explain step by step.
Add more will duplicate the contents of the table but this is just for demo use to show you can still trigger events with dynamic elements.
Discount will be deducted as a percent of the price.
$(document).on('input','.Calc',function(){
// Reset Total
var Total=0;
$('.Inputs').each(function(){
// Reset Price.
var Price=0;
// Reset Decution.
var Deduction=0;
// Price x Quantity
Price=parseFloat($(this).find(".Qty").val())*parseFloat($(this).find(".Price").val());
var Percent=parseFloat($(this).find(".Disc").val());
// If Discount is greater than 0 make deductions.
if(Percent>0){
// Calculate the discount Percent of the Price.
// Example 300*40/100 = 120
Deduction=Price*Percent/100;
// Minus discount from the price.
Price=Price-Deduction;
}
// Sub total, add Price to existing Total
Total=Total+Price;
// Display Price and savings "£0 (Save £0)"
$(this).find("span").html('£'+Price+' <small>(Save £'+Deduction+')</small>');
});
// Display New Total.
$('#Total').html('Sub Total £'+Total);
});
//--------- Clone / Append (Demo Use)
$('#More').on('click',function(){
// This is used to show you can run the functions even if the elements are dynamic.
// (This is very messy but it shows that it works)
var target = document.getElementById('MyForm');
var tr = document.createElement('tr');
tr.setAttribute('class', 'Inputs'); // Edit this
target.appendChild(tr);
var td1 = document.createElement('td');
tr.appendChild(td1);
td1.innerHTML='Qty';
var td2 = document.createElement('td');
tr.appendChild(td2);
td2.innerHTML='£';
var td3= document.createElement('td');
tr.appendChild(td3);
// Add inputs.
td3.innerHTML='Discount:';
var QTY = document.createElement('input');
var PRICE = document.createElement('input');
var DISC = document.createElement('input');
QTY.setAttribute('type','text');
QTY.setAttribute('class','Qty Calc');
QTY.setAttribute('value',1);
PRICE.setAttribute('type','text');
PRICE.setAttribute('class','Price Calc');
PRICE.setAttribute('value',0);
DISC.setAttribute('type','text');
DISC.setAttribute('class','Disc Calc');
DISC.setAttribute('value',0);
td1.appendChild(QTY);
td2.appendChild(PRICE);
td3.appendChild(DISC);
td3.innerHTML=td3.innerHTML+'% <span></span>';
});
/* CSS for Demo Use. */
.Qty{width:30px;}
.Price{width:70px;}
.Disc{width:30px;}
span{color:red;font-weight:bold;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="More">Add</button>
<table id="MyForm">
<tr class="Inputs">
<td>Qty<input type="text" class="Qty Calc" value="1"/></td>
<td> £<input type="text" class="Price Calc" value="0"/></td>
<td> Discount:<input type="text" class="Disc Calc" value="0"/>% <span></span></td>
</tr>
</table>
<span id="Total"></span>
If you have any questions about the source code above please leave a comment below and I will reply as soon as possible.
I hope this helps. Happy coding!
This is using jQuery
Update: Replaced clone() with createElement()

Related

Converting JavaScript Object to Float

I am currently trying to make an application where I can add up the columns of an HTML table. I am able to add inputs to the table but when I try to add up the columns I get, "NaN" error.
/* Function to calculate income */
function Add() {
// Variables from input field
var table = document.getElementById("Expenses");
var name = document.getElementById("Name").value;
var price = parseFloat(document.getElementById("Price").value);
if (price == "" && name == "") {
alert("Please enter in values.");
} else {
// Insert a default row from here:
var Entry = table.insertRow(-1);
var col0 = Entry.insertCell(0);
var col1 = Entry.insertCell(1);
col0.innerHTML = name;
col1.innerHTML = "$" + parseFloat(price);
document.getElementById("Name").value = "";
document.getElementById("Price").value = "";
console.log(typeof col1);
}
}
/* Function to add up last column */
function Calculate() {
var table = document.getElementById("Expenses");
var sumVal = 0;
var Entry = table.insertRow(-1);
var col0 = Entry.insertCell(0);
var col1 = Entry.insertCell(1);
for (var i = 1; i < table.rows.length; i++) {
sumVal += parseFloat(table.rows[i].cells[1]);
}
col0.innerHTML = "All Expenses";
col1.innerHTML = sumVal;
}
<div class="body">
<div class="container">
<div class="center">
<h3>Enter Expenses Below</h3>
<ul class="info">
<li>
<input type="text" placeholder="Name of Expense" id="Name">
</li>
<li>
<input type="number" min="0" placeholder="Price of Expense" id="Price">
</li>
</ul>
</div>
</div>
<table class="topmargin results-field" id="Expenses">
<tr>
<th>Name of Expense</th>
<th>Price of Expense</th>
</tr>
</table>
<div class="container1">
<div class="center1">
<button type="button" id="Add" onclick="Add()">Add</button>
<button type="button" id="Remove" onclick="Remove()">Remove</button>
<button type="button" id="Calculate" onclick="Calculate()">Calculate</button>
<button type="button" id="Print" onclick="window.print()">Print</button>
</div>
</div>
</div>
Any help is appreciated. Thank you.
Cell is a td element so we should get its innerHTML or innerText and remove '$' symbol from it. And for loop should be table.rows.length-1 because of last sum row. And it's clean now!
/* Function to calculate income */
function Add() {
// Variables from input field
var table = document.getElementById("Expenses");
var name = document.getElementById("Name").value;
var price = parseFloat(document.getElementById("Price").value);
if (price == "" && name == "") {
alert("Please enter in values.");
} else {
// Insert a default row from here:
var Entry = table.insertRow(-1);
var col0 = Entry.insertCell(0);
var col1 = Entry.insertCell(1);
col0.innerHTML = name;
col1.innerHTML = "$" + parseFloat(price);
document.getElementById("Name").value = "";
document.getElementById("Price").value = "";
console.log(typeof col1);
}
}
/* Function to add up last column */
function Calculate() {
var table = document.getElementById("Expenses");
var sumVal = 0;
var Entry = table.insertRow(-1);
var col0 = Entry.insertCell(0);
var col1 = Entry.insertCell(1);
for (var i = 1; i < table.rows.length-1; i++) {
sumVal += parseFloat(table.rows[i].cells[1].innerHTML.replace('$',''));
}
col0.innerHTML = "All Expenses";
col1.innerHTML = "$" + sumVal;
}
<div class="body">
<div class="container">
<div class="center">
<h3>Enter Expenses Below</h3>
<ul class="info">
<li>
<input type="text" placeholder="Name of Expense" id="Name">
</li>
<li>
<input type="number" min="0" placeholder="Price of Expense" id="Price">
</li>
</ul>
</div>
</div>
<table class="topmargin results-field" id="Expenses">
<tr>
<th>Name of Expense</th>
<th>Price of Expense</th>
</tr>
</table>
<div class="container1">
<div class="center1">
<button type="button" id="Add" onclick="Add()">Add</button>
<button type="button" id="Remove" onclick="Remove()">Remove</button>
<button type="button" id="Calculate" onclick="Calculate()">Calculate</button>
<button type="button" id="Print" onclick="window.print()">Print</button>
</div>
</div>
</div>

How do I make a dynamic drop down menu using JavaScript

I have it so you type in on a form a maximum number then it creates a table after clicking a button.
I want it so after you click the button to add the row it writes a drop down menu in the table that goes from 0 to the number you put in the form
This is my HTML code:
<html>
<head>
<title>Form Generator</title>
<link rel="stylesheet" type="text/css" href="../css/converter.css"/>
<script language="JavaScript" src="../js/exercise2.js" type="text/javascript">
</script>
</head>
<body>
<p>
<button class="button" data-modal="M2KM">Form Generator</button>
</p>
<div id="M2KM" class="modal">
<div class="modal-content">
<div class="form">
<a class="close">×</a>
<form action="">
<textarea rows="1" name="Section" id="Section" cols="10">Section</textarea>
<textarea rows="1" name="Max" id="Max" cols="10">Max</textarea>
<textarea rows="1" name="Comment" id="Comment" cols="10">Comment</textarea>
<textarea rows="1" name="Mark" id="Mark" cols="10">Mark</textarea>
<input type="button" value="Add Row" name="Add Row" onclick="conversionTable('table')" />
<input type="reset" value="Clear" name="Clear">
</form>
<div id="conversion">
<table id="table">
<thead>
<tr>
<th>Section</th>
<th>Max</th>
<th>Comment</th>
<th>Mark</th>
</tr>
</thead>
</table>
</div>
</div>
</div>
</div>
</body>
</html>
This is my JavaScript Code:
function conversionTable(tagId, from, to)
{
var section = document.getElementById("Section").value;
var max = document.getElementById("Max").value;
var comment = document.getElementById("Comment").value;
var mark = document.getElementById("Mark").value;
from = 0;
to = 1;
var total = 0;
var arr = [];
var conv = document.getElementById(tagId) ;
var pre = document.createElement("pre");
conv.appendChild(pre);
var body= conv.appendChild(document.createElement("tbody"));
for (var i=from; i<to; i++)
{ row = body.appendChild(document.createElement("tr"));
var data=row.appendChild(document.createElement("td"));
data.appendChild(document.createTextNode(section));
data=row.appendChild(document.createElement("td"));
data.appendChild(document.createTextNode(max));
var data=row.appendChild(document.createElement("td"));
data.appendChild(document.createTextNode(comment));
data=row.appendChild(document.createElement("select"));
data.setAttribute("id", "mySelect");
row.appendChild(data);
var z = document.createElement("option");
z.setAttribute("value", "volvocar");
var t = document.createTextNode("1");
z.appendChild(t);
document.getElementById("mySelect").appendChild(z);
total = total + mark;
var obj = {section: section, max: max, comment: comment, mark: mark};
arr.push(obj);
}
}
This is a screenshot showing test data:
Here's a simplified example that adds a select element with a number of options equal to the number entered by the user.
See comments in the code for an explanation of how it works.
// Identifies existing HTML elements
const maxInput = document.getElementById("max");
const button = document.getElementById("button");
const table = document.getElementById("table");
// Calls `addDropdown` when `button` is clicked
button.addEventListener("click", addDropdown);
// Defines the event listener
function addDropdown(event) { //(`event` object is available if we want it)
// Gets value from input
let max = parseInt(maxInput.value);
// Exits function early if maxInput doesn't have a number
if(!max){ return; }
// Defines the new elements
const row = document.createElement("tr");
const cell = document.createElement("td");
const dropdown = document.createElement("select");
// Enumerates options and adds them to the select element
let optNumber = -1;
while(++optNumber <= max){
let optionElement = document.createElement("option");
optionElement.value = "opt" + optNumber;
optionElement.innerHTML = "Option " + optNumber;
dropdown.appendChild(optionElement);
}
// Adds the elements to the page
cell.appendChild(dropdown);
row.appendChild(cell);
table.appendChild(row);
}
<label>
<span>Enter maximum value for dropdown:</span>
<input id="max" value="5" />
</label>
<br />
<button id="button">Add Dropdown in New Row</button>
<div id="container">
<table id="table"></table>
</div>

How can I make the user add a new field using a button using javascript?

I have a script posted down below, and I want the user to add a new field, when the new field gets added I want a new var to be added.
Live example:
User clicks on the "add new field"
var gets added below var Reason2 called Reason3, Reason4, etc.
"Reason Three: " +Reason3+ gets added below Reason Two on line 51.
I don't have an idea of how to do the above honestly.
<!DOCTYPE html>
<html lang="en">
<form name="TRF" method="post">
<p style="color:white">
<div class="container">
<div class="row">
<div class="col-lg-12">
<div class="jumbotron">
<h1 class="text-center">Accepted Format</h1>
<hr>
<div class="row">
<h6 class="text-uppercase"><strong><center>Accepted Format</center></strong></h6>
<table style="width:100%" id="theTable">
<tr>
<td>Applicant's Name:</td>
<td><input type="text" name="accname" size="75" placeholder="" required></td>
</tr>
<tr>
<td>Reason 1:</td>
<td><input type="text" name="R1" size="75" placeholder="" required></td>
</tr>
<tr>
<td id="bla">Reason 2:</td>
<td><input type="text" name="R2" size="75" placeholder="" required></td>
</tr>
</table>
<h3>CODE:</h3>
<textarea id="box" cols="100" rows="10"></textarea>
<p><a class="btn btn-success btn-lg" onclick="generateCode2()" role="button">GENERATE CODE</a></p>
</div>
<button id="newField">
add new field
</button>
</center>
</div>
</div>
</div>
</div>
<html>
<head>
<script>
function generateCode2() {
var AccoutName = document.forms["TRF"]["accname"].value;
var Reason1 = document.forms["TRF"]["R1"].value;
var Reason2 = document.forms["TRF"]["R2"].value;
document.getElementById("box").value =
"[center][img width=500 height=500]https://i.imgur.com/FuxDfcy.png[/img][/center]"+
"[hr]"+
"\n"+
"[b]Dear[/b] "+AccoutName+
"\n"+
"After reading your Application, Imperials staffs have decided to [color=green][b]Accept[/b][/color] you. "+
"\n"+
"Reason One: " +Reason1+
"\n"+
"Reason Two: " +Reason2+
"\n"+
"Welcome to the Family. "+
"\n"+
""
}
var newField = document.getElementById("newField");
var counter = 3;
function createNewField() {
var tr = document.createElement("tr");
var td1 = document.createElement("td");
var td2 = document.createElement("td");
td1.innerHTML = "Reason " + counter + ":";
var inp = document.createElement("input");
inp.type = "text";
inp.size = "75";
inp.name = "R" + counter;
inp.value=document.getElementById("box").value;
td2.appendChild(inp);
document.getElementById("theTable").appendChild(tr);
tr.appendChild(td1);
tr.appendChild(td2);
counter++;
}
newField.addEventListener("click", createNewField);
(function () {
var onload = window.onload;
window.onload = function () {
if (typeof onload == "function") {
onload.apply(this, arguments);
}
var fields = [];
var inputs = document.getElementsByTagName("input");
var textareas = document.getElementsByTagName("textarea");
for (var i = 0; i < inputs.length; i++) {
fields.push(inputs[i]);
}
for (var i = 0; i < textareas.length; i++) {
fields.push(textareas[i]);
}
for (var i = 0; i < fields.length; i++) {
var field = fields[i];
if (typeof field.onpaste != "function" && !!field.getAttribute("onpaste")) {
field.onpaste = eval("(function () { " + field.getAttribute("onpaste") + " })");
}
if (typeof field.onpaste == "function") {
var oninput = field.oninput;
field.oninput = function () {
if (typeof oninput == "function") {
oninput.apply(this, arguments);
}
if (typeof this.previousValue == "undefined") {
this.previousValue = this.value;
}
var pasted = (Math.abs(this.previousValue.length - this.value.length) > 1 && this.value != "");
if (pasted && !this.onpaste.apply(this, arguments)) {
this.value = this.previousValue;
}
this.previousValue = this.value;
};
if (field.addEventListener) {
field.addEventListener("input", field.oninput, false);
} else if (field.attachEvent) {
field.attachEvent("oninput", field.oninput);
}
}
}
}
})();
</script>
</head>
</color>
</font>
</div>
</div>
</div>
</html>
User clicks on the "add new field"
var gets added below var Reason2 called Reason3, Reason4, etc.
"Reason Three: " +Reason3+ gets added below Reason Two on line 51.
In Javascript it's possible to create html elements at runtime using the createElement() function. In your case we need to create quite a lot of individual elements to replicate the structure of the table. Those are <tr> <td> <input>.
The tr element needs to be added to the table, the td containing the text 'Reason #:' as well as the td holding the input element are childs of tr. To add a dynamically created element to the DOM, the appendChild() function is used.
The input element needs some special treatment because it contains an unique id. The two html-made elements you have are 'R1' and 'R2' - so a new one should follow that pattern and start with 3. This is done by setting up a global variable , appending it to the name and increment it afterwards.
Finally we need to add a 'Create new field' button.
Take a look at this example (you have to scroll down to see the button):
var newField = document.getElementById("newField");
var counter = 3;
function createNewField() {
var tr = document.createElement("tr");
var td1 = document.createElement("td");
var td2 = document.createElement("td");
td1.innerHTML = "Reason " + counter + ":";
var inp = document.createElement("input");
inp.type = "text";
inp.size = "75";
inp.name = "R" + counter;
td2.appendChild(inp);
document.getElementById("theTable").appendChild(tr);
tr.appendChild(td1);
tr.appendChild(td2);
counter++;
}
newField.addEventListener("click", createNewField);
function generateCode2() {
var AccoutName = document.forms["TRF"]["accname"].value;
var reasons = "";
for (var a = 1; a < counter; a++) {
reasons += "Reason " + a + ": " + document.forms["TRF"]["R" + a].value + "\n";
}
document.getElementById("box").value =
"[center][img width=500 height=500]https://i.imgur.com/FuxDfcy.png[/img][/center]" +
"[hr]" +
"\n" +
"[b]Dear[/b] " + AccoutName +
"\n" +
"After reading your Application, Imperials staffs have decided to [color=green][b]Accept[/b][/color] you. " +
"\n" + reasons +
"Welcome to the Family. " +
"\n" +
""
}
<form name="TRF" method="post">
<p style="color:white">
<div class="container">
<div class="row">
<div class="col-lg-12">
<div class="jumbotron">
<h1 class="text-center">Accepted Format</h1>
<hr>
<div class="row">
<h6 class="text-uppercase"><strong><center>Accepted Format</center></strong></h6>
<table style="width:100%" id="theTable">
<tr>
<td>Applicant's Name:</td>
<td><input type="text" name="accname" size="75" placeholder="" required></td>
</tr>
<tr>
<td>Reason 1:</td>
<td><input type="text" name="R1" size="75" placeholder="" required></td>
</tr>
<tr>
<td id="bla">Reason 2:</td>
<td><input type="text" name="R2" size="75" placeholder="" required></td>
</tr>
</table>
<h3>CODE:</h3>
<textarea id="box" cols="100" rows="10"></textarea>
<p><a class="btn btn-success btn-lg" onclick="generateCode2()" role="button">GENERATE CODE</a></p>
</div>
<button id="newField">
add new field
</button>
</center>
</div>
</div>
</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) {
.....
}

Form loosing dynamically created table after function returns

I have a simple HTML5 that is meant to be a calculator.
I fill up the field and click on submit. The script runs produces the table as you can see in the debug screenshot and then the next step the page is back again with form unfilled and no table on it.
I tried the return false after script but it is not working as desired...
After the javascript returns the debug goes back to the tag button and calls a javascript that seems to be of Chrome...
This behavior is happening in Chorme 47.0.2526.106 m old IE9 witch are the browsers I have here to test...
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="description" content="">
<meta name="author" content="">
<title>Calculadora</title>
</head>
<body>
<div class="jumbotron">
<form class="form-horizontal" method="post" >
<fieldset>
<!-- Form Name -->
<legend>Calculadora</legend>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="val_inicial">Valor Inicial</label>
<div class="col-md-4">
<input id="val_inicial" name="val_inicial" type="text" placeholder="Valor Inicial" class="form-control input-md" required="">
<span class="help-block">Type here your initial deposit</span>
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="val_perio">Valor de aplicação periódica</label>
<div class="col-md-4">
<input id="val_perio" name="val_perio" type="text" placeholder="Valor Recorrente" class="form-control input-md" required="">
<span class="help-block">Type here your recorrent deposit</span>
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="taxa_mensal">Taxa de rendimento mensal</label>
<div class="col-md-4">
<input id="taxa_mensal" name="taxa_mensal" type="text" placeholder="Taxa Mensal" class="form-control input-md" required="">
<span class="help-block">Type here the expected return tax</span>
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="num_periodos">Número de Períodos</label>
<div class="col-md-4">
<input id="num_periodos" name="num_periodos" type="text" placeholder="Número de Períodos" class="form-control input-md" required="">
<span class="help-block">Type here the number of periods for your calculations</span>
</div>
</div>
<!-- Button -->
<div class="form-group">
<label class="col-md-4 control-label" for="btn_calcular"></label>
<div class="col-md-4">
<button id="btn_calcular" name="btn_calcular" class="btn btn-primary" onclick="calcular();">Calcular</button>
</div>
</div>
<!-- Label -->
<div class="form-group" id="div_resultado" style="visibility:hidden;">
<label class="col-md-4 control-label" for="total">Valor Calculado</label>
<div class="col-md-4">
<input id="total" name="total" type="text" placeholder="Valor Calculado" class="form-control input-md" >
</div>
</div>
</fieldset>
</form>
</div>
<div class="row marketing">
<div class="col-lg-6" id="tableDiv">
<table border="1" id="resultado">
<thead>
<th>Período</th>
<th>Taxa</th>
<th>Saldo anterior</th>
<th>Aplicação</th>
<th>Saldo posterior</th>
</thead>
</table>
</div>
</div>
<footer class="footer">
<p>© 2015 Company, Inc.</p>
</footer>
<script src="./fatAcc.js" type="text/javascript"></script>
</body>
</html>
and the javascript fatAcc.js
function operadorCantoneira(i, t) {
var iPercent = i/100;
var resultado = (Math.pow(1+iPercent, t)-1)/iPercent;
return resultado.toFixed(5);
}
function calcular() {
var i = document.getElementById('taxa_mensal').value;
var t = document.getElementById('num_periodos').value;
var valorInicial = document.getElementById('val_inicial').value
var valorRecorrente = document.getElementById('val_perio').value
var valorCalculadoInicial = valorInicial * i/100;
var valorCalculado = valorCalculadoInicial * operadorCantoneira(i, t-1);
document.getElementById('total').value = valorCalculado.formatMoney(2,',', '.');
document.getElementById('div_resultado').style.visibility='visible';
geraTabelaResultadosMensais();
return false;
}
Number.prototype.formatMoney = function(c, d, t){
var n = this,
c = isNaN(c = Math.abs(c)) ? 2 : c,
d = d == undefined ? "." : d,
t = t == undefined ? "," : t,
s = n < 0 ? "-" : "",
i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "",
j = (j = i.length) > 3 ? j % 3 : 0;
return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
};
function geraTabelaResultadosMensais(){
//var tableDiv = document.getElementById('tableDiv');
var table = document.getElementById('resultado');
var t = Number(document.getElementById('num_periodos').value);
var i = Number(document.getElementById('taxa_mensal').value);
var valorInicial = Number(document.getElementById('val_inicial').value);
var valorRecorrente = Number(document.getElementById('val_perio').value);
var valorAcumulado = valorInicial;
//PRIMEIRA LINHA
var row = table.insertRow ();
var cell1 = row.insertCell();
var cell2 = row.insertCell();
var cell3 = row.insertCell();
var cell4 = row.insertCell();
var cell5 = row.insertCell();
cell1.innerHTML = 1;
cell2.innerHTML = i;
cell3.innerHTML = valorInicial;
cell4.innerHTML = valorRecorrente;
valorAcumulado = valorInicial * (1+i/100);
cell5.innerHTML = valorAcumulado.formatMoney(2,',', '.');
//O RESTANTE DAS LINHAS
for(var tempT=2; tempT<=t; tempT++){
row = table.insertRow();
cell1 = row.insertCell();
cell2 = row.insertCell();
cell3 = row.insertCell();
cell4 = row.insertCell();
cell5 = row.insertCell();
cell1.innerHTML = tempT;
cell2.innerHTML = i;
cell3.innerHTML = valorAcumulado.formatMoney(2,',', '.');
cell4.innerHTML = valorRecorrente.formatMoney(2,',', '.');
valorAcumulado = (Number(valorAcumulado) + Number(valorRecorrente))*(1 + i/100);
cell5.innerHTML = valorAcumulado.formatMoney(2,',', '.');
}
tableDiv.appendChild(table);
return false;
}
Clicking on button forces form to submit. If you don't specify button type it's default type is type="submit" which causes form to be submitted. You can add type="button" to button and it should work.
The better solution will be to use onsubmit event on form not onclick on button. Returning false from onsubmit will prevent form submition in all browsers.
Good code sample with possible workaround for Chrome was already given in this answer: JavaScript code to stop form submission

Categories

Resources