Convert amount into words with JavaScript - javascript

I need convert the total amount in to words with jquery in a script file.
I have the total value calculated and put int to id=(#grandT) and the same value should be converted in to words(Rupees/Indian numbering system) in textarea (#word)
https://en.wikipedia.org/wiki/Indian_numbering_system
Script File
$(document).ready(function() {
$(".input").keyup(function() {
var valp1 = +$(".prec1").val();
var valr1 = +$(".rate1").val();
var valq1 = +$(".qty1").val();
var valp2 = +$(".prec2").val();
var valr2 = +$(".rate2").val();
var valq2 = +$(".qty2").val();
$("#Gst1").val((valr1 * valq1) * valp1 / 100);
$("#Gst2").val((valr2 * valq2) * valp2 / 100);
});
$(".input").keyup(function() {
var val1 = +$(".rate1").val();
var val2 = +$(".qty1").val();
var val3 = +$(".rate2").val();
var val4 = +$(".qty2").val();
var valp1 = +$(".prec1").val();
var valp2 = +$(".prec2").val();
var valr1 = +$(".rate1").val();
var valr2 = +$(".rate2").val();
var valq1 = +$(".qty1").val();
var valq2 = +$(".qty2").val();
$("#result1").val(val1 * val2);
$("#result2").val(val3 * val4);
$("#grandT").val(((val1 * val2) + (val3 * val4)) + ("/-"));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<script type="text/javascript" src="jquery-1.9.1.js"></script>
<script type="text/javascript" src="Script.js"></script>
<link rel="stylesheet" href="StyleSheet.css">
</head>
<body>
<page size="A4">
<div class="rowmain">
<table>
<thead class="th1">
<tr>
<th>PRECENTAGE</th>
<th>RATE</th>
<th>QTY</th>
<th>GST <br> AMOUNT
</th>
<th>AMOUNT</th>
</tr>
</thead>
<tbody>
<tr>
<td valign="middle"><input type="number" class="input prec1" value="" style="width: 3em" name="pre"></td>
<td valign="middle"><input type="number" name="rate" class="input rate1" value="" style="width: 5em"></td>
<td valign="middle"><input type="number" name="qty" class="input qty1" value="" style="width: 5em"></td>
<td valign="middle"><input disabled="disabled" id="Gst1" style="width: 6.5em" name="gst"></td>
<td valign="middle"><input disabled="disabled" class="text-right" id="result1" name="result1" class="input result1" value="" style="width: 7.4em"></td>
</tr>
<tr>
<td valign="middle"><input type="number" class="input prec2" value="" style="width: 3em" name="pre"></td>
<td valign="middle"><input type="number" name="rate" class="input rate2" value="" style="width: 5em"></td>
<td valign="middle"><input type="number" name="qty" class="input qty2" value="" style="width: 5em"></td>
<td valign="middle"><input disabled="disabled" id="Gst2" style="width: 6.5em" name="gst2"></td>
<td valign="middle"><input disabled="disabled" class="text-right" id="result2" name="result2" class="input result2" style="width: 7.4em"></td>
</tr>
</tbody>
</table>
</div>
<div class="rowmain">
<div class="leftttext">
<table class="th1">
<tr>
<th>Rupees in Words</th>
<td><textarea id="word" rows="2" cols="60"></textarea></td>
</tr>
</table>
</div>
<div class="righttext">
<table>
<tr>
<th class="thG">Grand Total</th>
<td><input disabled="disabled" class="text1" id="grandT" value="" style="width: 8em"></td>
</tr>
</table>
</div>
</div>
</page>
</body>
</html>

Here's a working snippet of what you wanted to achieve, as already suggested the conversion to word is done by the snippet in answer here: Convert digits into words with JavaScript, I recommend you read and look at the published package if that's more useful for you.
/*
* taken from
* https://stackoverflow.com/questions/14766951/convert-digits-into-words-with-javascript
*/
var a = ['', 'one ', 'two ', 'three ', 'four ', 'five ', 'six ', 'seven ', 'eight ', 'nine ', 'ten ', 'eleven ', 'twelve ', 'thirteen ', 'fourteen ', 'fifteen ', 'sixteen ', 'seventeen ', 'eighteen ', 'nineteen '];
var b = ['', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'];
function inWords(num) {
if ((num = num.toString()).length > 9) return 'overflow';
n = ('000000000' + num).substr(-9).match(/^(\d{2})(\d{2})(\d{2})(\d{1})(\d{2})$/);
if (!n) return;
var str = '';
str += (n[1] != 0) ? (a[Number(n[1])] || b[n[1][0]] + ' ' + a[n[1][1]]) + 'crore ' : '';
str += (n[2] != 0) ? (a[Number(n[2])] || b[n[2][0]] + ' ' + a[n[2][1]]) + 'lakh ' : '';
str += (n[3] != 0) ? (a[Number(n[3])] || b[n[3][0]] + ' ' + a[n[3][1]]) + 'thousand ' : '';
str += (n[4] != 0) ? (a[Number(n[4])] || b[n[4][0]] + ' ' + a[n[4][1]]) + 'hundred ' : '';
str += (n[5] != 0) ? ((str != '') ? 'and ' : '') + (a[Number(n[5])] || b[n[5][0]] + ' ' + a[n[5][1]]) + 'only ' : '';
return str;
}
$(document).ready(function() {
$(".input").keyup(function() {
var valp1 = +$(".prec1").val();
var valr1 = +$(".rate1").val();
var valq1 = +$(".qty1").val();
var valp2 = +$(".prec2").val();
var valr2 = +$(".rate2").val();
var valq2 = +$(".qty2").val();
$("#Gst1").val((valr1 * valq1) * valp1 / 100);
$("#Gst2").val((valr2 * valq2) * valp2 / 100);
});
$(".input").keyup(function() {
var val1 = +$(".rate1").val();
var val2 = +$(".qty1").val();
var val3 = +$(".rate2").val();
var val4 = +$(".qty2").val();
var valp1 = +$(".prec1").val();
var valp2 = +$(".prec2").val();
var valr1 = +$(".rate1").val();
var valr2 = +$(".rate2").val();
var valq1 = +$(".qty1").val();
var valq2 = +$(".qty2").val();
$("#result1").val(val1 * val2);
$("#result2").val(val3 * val4);
var total = (val1 * val2) + (val3 * val4);
$("#grandT").val(total + "/-");
$("#word").val(inWords(total));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<script type="text/javascript" src="jquery-1.9.1.js"></script>
<script type="text/javascript" src="Script.js"></script>
<link rel="stylesheet" href="StyleSheet.css">
</head>
<body>
<page size="A4">
<div class="rowmain">
<table>
<thead class="th1">
<tr>
<th>PRECENTAGE</th>
<th>RATE</th>
<th>QTY</th>
<th>GST <br> AMOUNT
</th>
<th>AMOUNT</th>
</tr>
</thead>
<tbody>
<tr>
<td valign="middle"><input type="number" class="input prec1" value="" style="width: 3em" name="pre"></td>
<td valign="middle"><input type="number" name="rate" class="input rate1" value="" style="width: 5em"></td>
<td valign="middle"><input type="number" name="qty" class="input qty1" value="" style="width: 5em"></td>
<td valign="middle"><input disabled="disabled" id="Gst1" style="width: 6.5em" name="gst"></td>
<td valign="middle"><input disabled="disabled" class="text-right" id="result1" name="result1" class="input result1" value="" style="width: 7.4em"></td>
</tr>
<tr>
<td valign="middle"><input type="number" class="input prec2" value="" style="width: 3em" name="pre"></td>
<td valign="middle"><input type="number" name="rate" class="input rate2" value="" style="width: 5em"></td>
<td valign="middle"><input type="number" name="qty" class="input qty2" value="" style="width: 5em"></td>
<td valign="middle"><input disabled="disabled" id="Gst2" style="width: 6.5em" name="gst2"></td>
<td valign="middle"><input disabled="disabled" class="text-right" id="result2" name="result2" class="input result2" style="width: 7.4em"></td>
</tr>
</tbody>
</table>
</div>
<div class="rowmain">
<div class="leftttext">
<table class="th1">
<tr>
<th>Rupees in Words</th>
<td><textarea id="word" rows="2" cols="60"></textarea></td>
</tr>
</table>
</div>
<div class="righttext">
<table>
<tr>
<th class="thG">Grand Total</th>
<td><input disabled="disabled" class="text1" id="grandT" value="" style="width: 8em"></td>
</tr>
</table>
</div>
</div>
</page>
</body>
</html>

Here is a simple short method to convert numbers to words in English.
//----------------------------------------------------------------
function numToWords(num = 0) {
if (num==0) return "Zero";
num=("0".repeat(2*(num+="").length%3)+num).match(/.{3}/g);
let out="",T1=["","One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten","Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"],
T2=["","","Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety"],
SC=["","Thousand","Million","Billion","Trillion","Quadrillion"];
return num.forEach((n,i)=>{if(+n){let h=+n[0],t=+n.substring(1),S=SC[num.length-i-1];
out+=(out?" ":"")+(h?T1[h]+" Hundred":"")+(h&&t?" ":"")+(t<20?T1[t]:T2[+n[1]]+(+n[2]?"-":"")+T1[+n[2]]);
out+=(out && S?" ":"")+S;}}),out;}
//----------------------------------------------------------------
console.log(numToWords(0))
console.log(numToWords(22))
console.log(numToWords(1234))
console.log(numToWords(3354646))

Related

How to add dynamic value to dynamic generated table using javascript

I am making an EMI calculator where I want to calculate monthly installments and a table for each installment. You can see the result when you put the interest rate [example 9].
My question is how can I generate that table with some calculated value so each column will decrease the value from the principal. Like ai added an Image
here is an example: https://codepen.io/exclutips/pen/ZEvgXvb
function addTable(installment,amount,rate) {
var table = document.querySelector("DynamicTable");
var tableBody = document.getElementById('DynamicTable').getElementsByTagName('tbody')[0];
tableBody.innerHTML = "";
for (var i = 1; i < installment+1; i++) {
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for (var j = 1; j < 8 + 1; j++) {
var td = document.createElement('TD');
if(i <=12){
td.appendChild(document.createTextNode(amount));
tr.appendChild(td);
}
if(i > 12){
td.appendChild(document.createTextNode(rate));
tr.appendChild(td);
}
}
}
}
function Calculate() {
// Extracting value in the amount
var amount = document.querySelector("#loanAmount").value;
var rateValue = document.querySelector("#interestRate").value;
var year = document.querySelector("#loanPeriod").value;
var gracePeriod = document.querySelector("#gracePeriod").value;
var paymentperyear = document.querySelector("#paymentPerYear").value;
var instalment = document.querySelector("#instalment").value;
var graceInstalment = document.querySelector("#graceInstalment").value;
var payableTotalInt = document.querySelector("#payableTotal").value;
var principalMonthly = document.querySelector("#principalMonthly").value;
var interestMonthly = document.querySelector("#interestMonthly").value;
var interestEmployee = document.querySelector("#interestEmployee").value;
var govtSubsidy = document.querySelector("#govtSubsidy").value;
var employeeMonth = document.querySelector("#employeeMonth").value;
const rate = rateValue / 100;
//calculate months /
const months = year * paymentperyear;
//Number of instalment
const instalment_g = months - gracePeriod;
//Number of instalment with grace
const installmentGrace = year * paymentperyear;
// Calculating Payable Total interest
const interest = ((amount * rate) * (instalment_g + 1) / (paymentperyear * 2) + (amount * rate * gracePeriod) / paymentperyear);
//monthly payable Principal
const month_pay_principal = amount / instalment_g;
//monthly payable interest
const month_pay_interest = interest / instalment_g;
//Monthly Payable Interest by Employee
const month_pay_interest_emp = month_pay_interest * 4 / 9;
//Monthly Interest Subsidy by Govt.
const month_subsidy_interest_govt = month_pay_interest * 5 / 9;
//instalment for employee
const instalment_for_employee = month_pay_principal + month_pay_interest_emp;
//instalment for employee
const emi = month_pay_principal + month_pay_interest;
document.querySelector("#instalment").value = instalment_g;
document.querySelector("#graceInstalment").value = months;
//-----------------------------------------------------------
document.querySelector("#payableTotal").value = Math.round(interest);
document.querySelector("#principalMonthly").value = Math.round(month_pay_principal);
document.querySelector("#interestMonthly").value = Math.round(month_pay_interest);
document.querySelector("#interestEmployee").value = Math.round(month_pay_interest_emp);
document.querySelector("#govtSubsidy").value = Math.round(month_subsidy_interest_govt);
document.querySelector("#employeeMonth").value = Math.round(instalment_for_employee);
document.querySelector("#emi").value = Math.round(emi);
addTable(months,amount,month_pay_interest);
}
//Calculate dynamic table with interest
function addTable(install,amount,rate) {
var table = document.querySelector("DynamicTable");
var tableBody = document.getElementById('DynamicTable').getElementsByTagName('tbody')[0];
tableBody.innerHTML = "";
for (var i = 1; i < install + 1; i++) {
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for (var j = 1; j < 8 + 1; j++) {
var td = document.createElement('TD');
if(i <=12){
td.appendChild(document.createTextNode(Math.round(amount)));
tr.appendChild(td);
}
if(i > 12){
td.appendChild(document.createTextNode(Math.round(rate)));
tr.appendChild(td);
}
}
}
}
.form-control:focus {
color: #212529;
background-color: #c5ffd6;
border-color: #86b7fe;
outline: 0;
box-shadow: none;
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
<div class="container">
<div class="row p-3 my-4 bg-light">
<div class="col-md-6">
<form action="" method="post">
<div class="row align-items-center g-3">
<div class="col-auto">
<table class="table">
<tbody>
<tr>
<td>Loan Amount</td>
<td><input onchange="Calculate()" type="number" class="form-control form-control-sm" id="loanAmount" value="100000" required></td>
</tr>
<tr>
<td>Interest Rate(%)</td>
<td><input onchange="Calculate()" type="text" class="form-control form-control-sm" id="interestRate" required></td>
</tr>
<tr>
<td>Loan Period( in Years )</td>
<td><input onchange="Calculate()" type="number" class="form-control form-control-sm" id="loanPeriod" value="2" required></td>
</tr>
<tr>
<td>Grace Period </td>
<td><input onchange="Calculate()" type="number" class="form-control form-control-sm" id="gracePeriod" value="12" required></td>
</tr>
<tr>
<td>Payment Per Year </td>
<td><input onchange="Calculate()" type="number" class="form-control form-control-sm" id="paymentPerYear" value="12" required></td>
</tr>
<tr>
<td>No. of Installment </td>
<td><input onchange="Calculate()" type="number" class="form-control form-control-sm" id="instalment" readonly></td>
</tr>
<tr>
<td>No. of Installments(With Grace Period)</td>
<td><input onchange="Calculate()" type="number" class="form-control form-control-sm" id="graceInstalment" readonly></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<div class="col-md-6">
<div class="row align-items-center g-3">
<div class="col-auto">
<table id="inputTable" class="table">
<tbody>
<tr>
<td>Payable Total Interest</td>
<td><input onchange="Calculate()" type="number" class="form-control form-control-sm" id="payableTotal" readonly></td>
</tr>
<tr>
<td>Monthly Payable Principal</td>
<td><input onchange="Calculate()" type="number" class="form-control form-control-sm" id="principalMonthly" readonly></td>
</tr>
<tr>
<td>Monthly Payable Interest</td>
<td><input onchange="Calculate()" type="number" class="form-control form-control-sm" id="interestMonthly" readonly></td>
</tr>
<tr>
<td>Monthly Payable Interest by Employee</td>
<td><input onchange="Calculate()" type="number" class="form-control form-control-sm" id="interestEmployee" readonly></td>
</tr>
<tr>
<td>Monthly Interest Subsidy by Govt.</td>
<td><input onchange="Calculate()" type="number" class="form-control form-control-sm" id="govtSubsidy" readonly></td>
</tr>
<tr>
<td>Employee to pay Monthly payment</td>
<td><input onchange="Calculate()" type="number" class="form-control form-control-sm" id="employeeMonth" readonly></td>
</tr>
<tr>
<td class="text-danger">EMI</td>
<td><input onchange="Calculate()" type="number" class="form-control form-control-sm text-danger" id="emi" readonly></td>
</tr>
</tbody>
</table>
</div>
</div>
</form>
</div>
</div>
</div>
<hr>
<div class="container">
<div class="row p-3 bg-light">
<div class="col-md-12">
<table id="DynamicTable" class="table">
<thead>
<tr>
<th>No of Months</th>
<th>Outstandng Principals</th>
<th>Monthly Payable Principal</th>
<th>Interest Accrued</th>
<th>Monthly Payable Interest</th>
<th>Inyerest Payable by employee</th>
<th>Interest subsidy by Govt.</th>
<th>EMI</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>

Sum Javascript multiple fields

I have problem again with javascript, i want to ask how to sum from fields?
where is the problem?
I am trying to sum all my fields using getElementsByName and getElementsById. I want to show total sum of values entered in sub total input boxes in next input box named total without refreshing page.
Can anyone will help me to figure it out..?
Here my code
$(document).on('keyup', '.input', function() {
var num1 = $(this).parents('tr:first').find('.input:first').val();
var num2 = $(this).parents('tr:first').find('.input:last').val();
$(this).parents('tr:first').find('.sub-total').val(to_rupiah(num1 * num2));
var arr = document.getElementsByName('.sub-total');
var tot = 0;
for (var i = 0; i < arr.length; i++) {
if (parseInt(arr[i].value))
tot += parseInt(arr[i].value);
}
document.getElementById('TotalBayar').value = tot;
});
$(document).ready(function() {
var index = 2;
$("#addCF").click(function() {
$("#customFields").append('<tr><td>' + index + '</td><td><input class="form-control" name="kode_barang[]" placeholder="Ketik Kode / Nama Barang" type="text"></td><td><input class="form-control input input1" name="harga_satuan[]" id="input1" value="" type="text"></td><td><input class="form-control input input2" id="input2" name="jumlah_beli[]" type="text"></td><td><input class="form-control sub-total" name="sub_total[]" onblur="findTotal()" value="" id="output" type="text"></td><td><button class="remCF"><i class="fa fa-times" style="color:red;"></i></button></td></tr>');
index++;
});
$("#customFields").on('click', '.remCF', function() {
$(this).parent().parent().remove();
});
});
function to_rupiah(angka) {
var rev = parseInt(angka, 10).toString().split('').reverse().join('');
var rev2 = '';
for (var i = 0; i < rev.length; i++) {
rev2 += rev[i];
if ((i + 1) % 3 === 0 && i !== (rev.length - 1)) {
rev2 += '.';
}
}
return 'Rp. ' + rev2.split('').reverse().join('');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<table class='table table-bordered' id='customFields'>
<thead>
<tr>
<th style='width:35px;'>#</th>
<th style='width:210px;'>Nama Barang</th>
<th style='width:120px;'>Harga</th>
<th style='width:75px;'>Qty</th>
<th style='width:125px;'>Sub Total</th>
<th style='width:40px;'></th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>
<input class="form-control" name="kode_barang[]" id="cariBrg" placeholder="Ketik Kode / Nama Barang" type="text">
</td>
<td><input class="form-control input" name="harga_satuan[]" id="input1" value="" type="text"></td>
<td><input class="form-control input" id="input2" name="jumlah_beli[]" type="text"></td>
<td><input class="form-control sub-total" name="sub_total[]" id="output" onblur="findTotal()" type="text"></td>
<td><button class="remCF"><i class="fa fa-times" style="color:red;"></i></button></td>
</tr>
</tbody>
</table>
<div class='alert alert-info TotalBayar'>
<button id='addCF' class='btn btn-default pull-left'><i class='fa fa-plus fa-fw'></i> Baris Baru (F7)</button>
<h2>Total : <span id='TotalBayar'>0</span></h2>
Please Help
getElementsByName(".sub-total") looks for elements with name=".sub-total", but you don't have that, it's a class. You can use $(".sub-total") to get these elements and loop over them.
document.getElementById('TotalBayar').value = tot;
won't work because TotalBayar is a DIV, and .value is only valid for inputs. Use $("#TotalBayar").text(tot) to set its contents.
You also can't just call parseInt() on the value in the sub-total fields, because they begin with Rp.. I've used a regular expression to get the number out of the value.
BTW, instead of .parents("tr:first") you can use .closest("tr").
$(document).on('keyup', '.input', function() {
var num1 = $(this).closest('tr').find('.input:first').val();
var num2 = $(this).closest('tr').find('.input:last').val();
$(this).closest('tr').find('.sub-total').val(to_rupiah(num1 * num2));
var arr = document.getElementsByName('.sub-total');
var tot = 0;
$(".sub-total").each(function() {
var val = parseInt($(this).val().match(/\d+/)[0]);
if (val) {
tot += val;
}
});
$('#TotalBayar').text(tot);
});
$(document).ready(function() {
var index = 2;
$("#addCF").click(function() {
$("#customFields").append('<tr><td>' + index + '</td><td><input class="form-control" name="kode_barang[]" placeholder="Ketik Kode / Nama Barang" type="text"></td><td><input class="form-control input input1" name="harga_satuan[]" id="input1" value="" type="text"></td><td><input class="form-control input input2" id="input2" name="jumlah_beli[]" type="text"></td><td><input class="form-control sub-total" name="sub_total[]" onblur="findTotal()" value="" id="output" type="text"></td><td><button class="remCF"><i class="fa fa-times" style="color:red;"></i></button></td></tr>');
index++;
});
$("#customFields").on('click', '.remCF', function() {
$(this).parent().parent().remove();
});
});
function to_rupiah(angka) {
var rev = parseInt(angka, 10).toString().split('').reverse().join('');
var rev2 = '';
for (var i = 0; i < rev.length; i++) {
rev2 += rev[i];
if ((i + 1) % 3 === 0 && i !== (rev.length - 1)) {
rev2 += '.';
}
}
return 'Rp. ' + rev2.split('').reverse().join('');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<table class='table table-bordered' id='customFields'>
<thead>
<tr>
<th style='width:35px;'>#</th>
<th style='width:210px;'>Nama Barang</th>
<th style='width:120px;'>Harga</th>
<th style='width:75px;'>Qty</th>
<th style='width:125px;'>Sub Total</th>
<th style='width:40px;'></th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>
<input class="form-control" name="kode_barang[]" id="cariBrg" placeholder="Ketik Kode / Nama Barang" type="text">
</td>
<td><input class="form-control input" name="harga_satuan[]" id="input1" value="" type="text"></td>
<td><input class="form-control input" id="input2" name="jumlah_beli[]" type="text"></td>
<td><input class="form-control sub-total" name="sub_total[]" id="output" onblur="findTotal()" type="text"></td>
<td><button class="remCF"><i class="fa fa-times" style="color:red;"></i></button></td>
</tr>
</tbody>
</table>
<div class='alert alert-info TotalBayar'>
<button id='addCF' class='btn btn-default pull-left'><i class='fa fa-plus fa-fw'></i> Baris Baru (F7)</button>
<h2>Total : <span id='TotalBayar'>0</span></h2>

Edit specific row and reset particular fields of a form not working

I have created a form, here when click on edit button from a dynamically created table it is not fetching the form values.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title> Generate Challan </title>
<link type="text/css" href="styles.css" rel="stylesheet" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="http://code.google.com/p/jquery-json/downloads/detail?name=jquery.json-2.2.min.js"></script>
<script type="text/javascript">
data = new Array();
$(document).ready(function(){
$(".addbutton").click(function() {
var row = new Array(12);
row[0] = $("#txtbox1").val();
row[1] = $("#txtbox2").val();
row[2] = $("#txtbox3").val();
row[3] = $("#txtbox4").val();
row[4] = $("#H1").val();
row[5] = $("#I1").val();
row[6] = $("#G1").val();
row[7] = $("#J1").val();
row[8] = $("#B1").val();
row[9] = $("#C1").val();
row[10] = $("#D1").val();
row[11] = $("#E1").val();
data.push(row);
refresh();
});
$('#myform')[0].reset(); //reset form stmt
//Edit function
var $tds = null;
$('#datatable').on('click', 'td:last-child', function (e) {
var $tr = $(this).parent(),
$tds = $tr.children(),
sname = $tds.eq(0).text().trim(),
mon = $tds.eq(1).text().trim();
year = $tds.eq(2).text().trim();
$('#G1 option').each(function () {
if ($(this).text().trim() == sname) {
$(this).prop('selected', true);
return false;
}
});
$('#H1 option').each(function () {
if ($(this).text().trim() == mon) {
$(this).prop('selected', true);
return false;
}
});
$('#I1 option').each(function () {
if ($(this).text().trim() == year) {
$(this).prop('selected', true);
return false;
}
});
$('#J1').val($tds.eq(3).text().trim())
$('#E1').val($tds.eq(4).text().trim())
e.preventDefault();
});
$("#myform").submit(function(){
var val = $.toJSON(data);
$("#data").attr("value",val);
if(data.length == 0){
alert("Table is empty !");
return false;
}else{
return true;
}
});
});
function refresh(){
$("#datatable").find("tr:gt(1)").remove();
publishtable();
}
function publishtable(){
for(var c=0;c<data.length;c++){
var trow = $('<tr valign="middle">').addClass("contact");
$("<td>").text(c+1).appendTo(trow);
for(var i=0;i<12;i++){
$("<td>").text(data[c][i]).appendTo(trow);
}
var abutton = $('<input type="button" class="editrow" value="Edit">');
var acell = $("<td>");
abutton.appendTo(acell);
acell.appendTo(trow);
$("#datatable").append(trow);
}
}
//Summation
function sum() {
var txtFirstNumberValue = document.getElementById('B1').value;
var txtSecondNumberValue = document.getElementById('C1').value;
var txtThirdNumberValue = document.getElementById('D1').value;
var result = parseFloat(txtFirstNumberValue) + parseFloat(txtSecondNumberValue) + parseFloat(txtThirdNumberValue);
if (!isNaN(result)) {
document.getElementById('E1').value = result;
}
}
</script>
</head>
<body>
<h2><center>Sample Form</center></h2>
<h5><center>(Rule 23(1) &AMP; Rule 24(1))</center></h5>
<br/><br/>
<table border="0">
<tr>
<td><label for="name">Received from Shri:</label></td>
<td><input type="text" name="name" id="txtbox1" class="txtbox"> </td>
</tr>
<tr>
<td><label for="address">Address:</label></td>
<td><input type="text" name="address" id="txtbox2" class="txtbox"> </td>
</tr>
<tr>
<td><label for="address">Email:</label></td>
<td><input type="text" name="email" id="txtbox3" class="txtbox"> </td>
</tr>
<tr>
<td><label for="mobileNo">Mobile No:</label></td>
<td><input type="text" name="mobile" id="txtbox4" class="txtbox"> </td>
</tr>
<tr>
<td> <label for="month">Month:</label></td>
<td><select name="month" id="H1">
<option>Select Month</option>
<option>January</option>
<option>February</option>
<option>March</option>
<option>April</option>
<option>May</option>
<option>June</option>
<option>July</option>
<option>August</option>
<option>September</option>
<option>October</option>
<option>November</option>
<option>December</option>
</select></td>
<td><label for="year">Year:</label></td>
<td><select name="year" id="I1">
<option>Select Year</option>
<option>2014</option>
<option>2015</option>
<option>2016</option>
<option>2017</option>
</select><td>
</tr>
<tr>
<td><label for="serviceName">Service Name:</label></td>
<td><select name="G1" id="G1">
<option>services</option>
</select></td>
</tr>
<tr>
<td><label for="details">Details:</label></td>
<td><input type="text" name="details" id="J1" class="txtbox" ></td>
</tr>
<tr>
<td><label for="tax">Tax:</label></td>
<td><input type="text" name="tax" id="B1" value="" class="txt" onkeyup="sum();" /></td>
</tr>
<tr>
<td><label for="cess">Cess:</label></td>
<td><input type="text" name="cess" id="C1" value="" class="txt" onkeyup="sum();" /></td>
</tr>
<tr>
<td><label for="penalty">Interest/Penalty:</label></td>
<td><input type="text" name="penalty" id="D1" value="" class="txt" onkeyup="sum();" /></td>
</tr>
<tr>
<td><label for="total">Total:</label></td>
<td><input type="text" name="total" id="E1" value="" class="txtbox" /></td>
</tr>
<td>
<input type="button" name="mybutton" class="addbutton" id="addbutton" value="Add">
</td>
</tr>
</table>
<br/>
<br/>
<br/><br/><br/>
<table id="datatable" class="contacts" border="1">
<thead>
<tr>
<td class="contactDept" colspan="13">Generated rows</td>
</tr>
</thead>
<tbody>
<tr class="contact_head">
<td>S.No.</td>
<td>Name</td>
<td>Address</td>
<td>Email</td>
<td>Mobile</td>
<td>Month</td>
<td>Year</td>
<td>Service</td>
<td>Details</td>
<td>Tax</td>
<td>Cess</td>
<td>Penalty</td>
<td>Total</td>
<!--<td><a href="#" >Edit</a></td>-->
</tr>
</tbody>
</table>
<br/>
<form id="myform" action="save/saveTable.action" method="post">
<input type="hidden" id="data" name="data">
<input type="submit" name="submitbutton" class="submitbutton" id="submitbutton" value="Submit Form">
</form>
Here when click on add, form values are displaying on the table. When click on submit button, I am passing the table(dynamically generated table) to some action class. Before submitting the table I have to perform edit operation. I have written a code for edit function but unable to edit. Please help me to solve..
You made a mistake in your var declaration.
For exemple, you have written mon = $tds.eq(1).text().trim();
It should be mon = $tds.eq(5).text().trim();
Because $tds.eq(1) is the name, not the month.
That's why
$('#H1 option').each(function () {
if ($(this).text().trim() == mon) {
$(this).prop('selected', true);
return false;
}
});
never appends.
Please see this working demo
UpDate 1 :
$('#datatable').on('click', 'td:last-child', function (e) {
var $tr = $(this).parent(),
$tds = $tr.children(),
name = $tds.eq(1).text().trim(),
adress = $tds.eq(2).text().trim(),
email = $tds.eq(3).text().trim(),
mobile = $tds.eq(4).text().trim(),
mon = $tds.eq(5).text().trim(),
year = $tds.eq(6).text().trim(),
service = $tds.eq(7).text().trim(),
details = $tds.eq(8).text().trim(),
tax = $tds.eq(9).text().trim(),
cess = $tds.eq(10).text().trim(),
penalty = $tds.eq(11).text().trim(),
sum = $tds.eq(12).text().trim();
...

Calculate Tax/TDR automatically in web form

I am calculating TAX/TDR automatically in the form.
But, it is not working. What am I doing wrong here?
The form tab includes :
Amount : user entered
Card type : select option
Visa (add 20% to amount)
Amex card(add 17.5% to amount)
other (add 15% to amount)
Grand Total : Amount + selected card type % amount
<html>
<head>
<script>
var calcObject = {
amountNull : '0.00',
amountTax : '0.00',
amountTotal : '0.00',
};
run : function() {
var amount = $('#amount').val();
var tax = $('#tax').val();
var included = $('#tax_included').is(':checked');
if (amount !== '' && tax !== '') {
if (included) {
var amountNew = amount / ((tax / 100) + 1);
calcObject.amountTax = parseFloat(amount) - parseFloat(amountNew);
calcObject.amountTotal = amountNew.toFixed(2);
} else {
calcObject.amountTax = (amount * tax) / 100;
calcObject.amountTotal = parseFloat(amount) + parseFloat(calcObject.amountTax);
}
$('#tax_amount').val(parseFloat(calcObject.amountTax).toFixed(2));
$('#total_amount').val(parseFloat(calcObject.amountTotal).toFixed(2));
} else {
$('#tax_amount').val(calcObject.amountNull);
$('#total_amount').val(calcObject.amountNull);
}
}
$(function() {
$('#amount').keyup(function() {
calcObject.run();
});
$('#tax_included').click(function() {
calcObject.run();
});
$('#tax').change(function() {
calcObject.run();
});
});
</script>
</head>
<body>
<form id="calculator" method="post">
<table class="tbl_insert">
<tr>
<th><label for="amount">Amount:</label></th>
<td>
<input type="text" name="amount" id="amount" value="" class="field" />
</td>
</tr>
<tr>
<th><label for="tax_included">TDR included?:</label></th>
<td>
<input type="checkbox" name="tax_included" id="tax_included" />
</td>
</tr>
<tr>
<th><label for="tax">Card Type :</label></th>
<td>
<select name="tax" id="tax" class="select">
<option value="20">VISA</option>
<option value="17.5">Amex card</option>
<option value="15">other</option>
</select>
</td>
</tr>
<tr>
<th><label for="tax_amount">VAT/Tax:</label></th>
<td>
<input type="text" name="tax_amount" id="tax_amount"
value="0.00" class="field" disabled="disabled" />
</td>
</tr>
<tr>
<th><label for="total_amount">Total:</label></th>
<td>
<input type="text" name="total_amount" id="total_amount"
value="0.00" class="field" disabled="disabled" />
</td>
</tr>
</table>
</form>
</body>
</html>
You have several errors.
Syntax error with object calcObject definition
Jquery is not included
I fixed them and this will work...
JSFIDDLE DEMO
<html>
<head>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<script>
var calcObject = {
amountNull : '0.00',
amountTax : '0.00',
amountTotal : '0.00',
run : function() {
var amount = $('#amount').val();
var tax = $('#tax').val();
var included = $('#tax_included').is(':checked');
if (amount !== '' && tax !== '') {
if (included) {
var amountNew = amount / ((tax / 100) + 1);
calcObject.amountTax = parseFloat(amount) - parseFloat(amountNew);
calcObject.amountTotal = amountNew.toFixed(2);
} else {
calcObject.amountTax = (amount * tax) / 100;
calcObject.amountTotal = parseFloat(amount) + parseFloat(calcObject.amountTax);
}
$('#tax_amount').val(parseFloat(calcObject.amountTax).toFixed(2));
$('#total_amount').val(parseFloat(calcObject.amountTotal).toFixed(2));
} else {
$('#tax_amount').val(calcObject.amountNull);
$('#total_amount').val(calcObject.amountNull);
}
}
};
$(function() {
$('#amount').keyup(function() {
calcObject.run();
});
$('#tax_included').click(function() {
calcObject.run();
});
$('#tax').change(function() {
calcObject.run();
});
});
</script>
</head>
<body>
<form id="calculator" method="post">
<table class="tbl_insert">
<tr>
<th><label for="amount">Amount:</label></th>
<td>
<input type="text" name="amount" id="amount" value="" class="field" />
</td>
</tr>
<tr>
<th><label for="tax_included">TDR included?:</label></th>
<td>
<input type="checkbox" name="tax_included" id="tax_included" />
</td>
</tr>
<tr>
<th><label for="tax">Card Type :</label></th>
<td>
<select name="tax" id="tax" class="select">
<option value="20">VISA</option>
<option value="17.5">Amex card</option>
<option value="15">other</option>
</select>
</td>
</tr>
<tr>
<th><label for="tax_amount">VAT/Tax:</label></th>
<td>
<input type="text" name="tax_amount" id="tax_amount"
value="0.00" class="field" disabled="disabled" />
</td>
</tr>
<tr>
<th><label for="total_amount">Total:</label></th>
<td>
<input type="text" name="total_amount" id="total_amount"
value="0.00" class="field" disabled="disabled" />
</td>
</tr>
</table>
</form>
</body>
</html>

Currency Converter Not Converting

The Currency converter up top works, but the table based one is a dead duck.
I need a value to be entered at Enter Amount of US Dollars and to be displayed in the corresponding value fields.
Here's the code:
<html>
<head>
<title>Convert US Dollars to Euros 2</title>
</head>
<body>
<form>
<table border="1">
<tbody>
<tr>
<th colspan="3">Monetary Exchange Rates
</th>
</tr>
<tr>
<th>Currency
</th>
<th>Rate
</th>
<th>Value
</th>
</tr>
<tr>
<td>British Pound
</td>
<td><input type="text" style="text-align: right;"
name="bp" value="0.62905" size="12" disabled="true" />
</td>
<td><input type="text" id="BP" value=""></td>
</tr>
<tr>
<td>Canadian Dollar
</td>
<td><input type="text" style="text-align: right;"
name="cd" value="0.98928" size="12" disabled="true" />
</td>
<td><input type="text" id="CD" value=""></td>
</tr>
<tr>
<td>Euro
</td>
<td><input type="text" style="text-align: right;"
name="eu" value="0.79759" size="12" disabled="true" />
</td>
<td><input type="text" id="EU" value=""></td>
</tr>
<tr>
<td>Japanese Yen
</td>
<td><input type="text" style="text-align: right;"
name="jy" value="78.5461" size="12" disabled="true" />
</td>
<td><input type="text" id="JY" value=""></td>
</tr>
<tr>
<td>Mexican Peso
</td>
<td><input type="text" style="text-align: right;"
name="mp" value="13.0729" size="12" disabled="true" />
</td>
<td><input type="text" id="MP" value=""> <!--
td-->
</td>
</tr>
<tr>
<td colspan="2"><b>Enter Amount of U.S. Dollars</b>
</td>
<td>
<input type="text" id="amount" name="amount" size="10" value="1" />
</td>
</tr></tbody>
</table> <br />
<input type="button" value="Calculate" onclick="calculate();">
<input type="reset" value="Reset" />
</form>
<script type="text/javascript">
var BP = '0.62905';
var CD = '0.98928';
var EU = '0.79759';
var JY = '78.5431';
var MP = '13.0729';
function calculate() {
var amount = parseFloat(document.getElementById("amount").value);
// var e = document.getElementById("select");
var select = e.options[e.selectedIndex].value;
var select = document.getElementById("select");
var result = document.getElementById("result");
if(select.options[select.selectedIndex].value=="BP")
if (select.value === "USD to EUR") {
result.value = (amount * 0.7003).toFixed(2);
}
if (select.value === "EUR to USD") {
result.value = (amount * 1.4283).toFixed(2);
}
if (select.value === "0.62905") {
result.value = (amount * 0.62905).toFixed(2);
}
}
</script>
</body>
</html>
Any help would be greatly appreciated.
ID's should be unique, you cannot use same ID multiple times, and your select value does not work, change:
var select = document.getElementById("select");
to
var e = document.getElementById("select");
var select = e.options[e.selectedIndex].value;
Having dropped the select, the script you're looking for is:
<script type="text/javascript">
var BP = '0.62905';
var CD = '0.98928';
var EU = '0.79759';
var JY = '78.5431';
var MP = '13.0729';
function calculate() {
var amount = parseFloat(document.getElementById("amount").value);
document.getElementById("BP").value = (amount * BP).toFixed(2);
document.getElementById("CD").value = (amount * CD).toFixed(2);
document.getElementById("EU").value = (amount * EU).toFixed(2);
document.getElementById("JY").value = (amount * JY).toFixed(2);
document.getElementById("MP").value = (amount * MP).toFixed(2);
}
</script>
We wouldn't want to list those out explicitly like that for anything large-scale; we'd build a list and iterate through it. But I think writing it out this way answers your immediate question better without muddying the waters for you.
Try this code
if(select.options[select.selectedIndex].value=="your value")

Categories