Populate table fields based on user input - javascript

I have to make an app, that takes a user input field, and then populates a table, according to some calculations. However, I don't understant how can I do this calculations to appear as a result in the field of the table. Can someone help me please?
Here is my code;
function countbase() {
let count = 0;
var input = document.getElementById('sequence').value;
const inputLen = input.length;
document.getElementById('bcount').value = GC_Content;
}
table,
th,
td {
border: 1px solid black;
border-collapse: collapse;
}
<h2>Calculater example</h2>
<label for="sequence"> Name field</label>
<br>
<br>
<textarea id="sequence" name="sequence" placeholder="Enter sequence" rows="2" cols="50">
</textarea>
<br><br>
<button onclick="countbase();">Check </button>
<br><br>
<table style="width:100%" id="values">
<tr>
<th colspan="2"> Results</th>
</tr>
<tr>
<td align="center"><span><b>Lenght Count:</b></span></td>
<td align="center"><span id="bcount"></span></td>
</tr>
<tr>
<td align="center"><span><b>Word Count :</b></span></td>
<td><b><span id="GC"></span></b></td>
</tr>
</table>

From your line:
document.getElementById('bcount').value = GC_Content;
Here GC_Content isn't defined, I guess you trying to set the inputLen variable.
That said, to change the content of a <span>, use innerHTML:
Change span text?
To get the 'word count', we can use split(' ') to create an array of the input string, then set the .length of that array as the content of the <span>
function countbase(){
// Get input element
const input = document.getElementById('sequence').value;
// Set length
document.getElementById('bcount').innerHTML = input.length;
// Set word count
document.getElementById('GC').innerHTML = input.split(' ').length;
}
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
<h2>Calculater example</h2>
<label for="sequence"> Name field</label>
<br>
<br>
<textarea id="sequence" name="sequence" placeholder= "Enter sequence" rows="2" cols="50">
</textarea>
<br><br>
<button onclick="countbase();">Check </button>
<br><br>
<table style="width:100%" id="values">
<tr>
<th colspan="2"> Results</th>
</tr>
<tr >
<td align="center"><span><b>Lenght Count:</b></span></td>
<td align="center"><span id="bcount"></span></td>
</tr>
<tr>
<td align="center"><span><b>Word Count :</b></span></td>
<td><b><span id="GC"></span></b></td>
</tr>
</table>

You can use Array.split() method and then get length of result array
let GC_Content = input.split(" ").length //splits input by spaces and count length of result array

Related

How to generate table from HTML?

So, I have to generate multiple tables from the HTML code. I can be generating multiple tables using pure javascript code but its too difficult to assign ids and getting its value. as I wrote javascript function generate_table
so I have created one sample HTML table from that HTML TAble how to generate the same Table again(multiple times). I have written too much javascript code for tables TD and TR. How to reduce that code.
I have many tables I want to regenerate the specific table so I cant use <table> tag. Any hint ? code sample ?
function generate_table() {
// get the reference for the body
var body = document.getElementsByTagName('body')[0];
// creates a <table> element and a <tbody> element
var tbl = document.createElement('table');
var tblBody = document.createElement('tbody');
// creating all cells
for (var i = 0; i < 1; i++) {
var seqnumber = 1;
var seq = +1;
// creates a table row
var row2 = document.createElement('tr');
//====== table first row data =======//
var seq = document.createElement('td');
var seqText = document.createTextNode('Seq');
var l = document.createElement('td');
var seqText1 = document.createElement('input');
//===== seq generator =====//
seq.appendChild(seqText);
row2.appendChild(seq);
l.appendChild(seqText1);
row2.appendChild(l);
// add the row to the end of the table body
tblBody.appendChild(row2);
}
// put the <tbody> in the <table>
tbl.appendChild(tblBody);
// appends <table> into <body>
body.appendChild(tbl);
// sets the border attribute of tbl to 2;
tbl.setAttribute('border', '2');
}
td,
th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
<h3> TABLE FROM JAVA SCRIPT</h3>
<input type="button" value="Generate a table." onclick="generate_table()" />
<h3> TABLE FROM HTML</h3>
<table id="table6">
<tr>
<th colspan="2">Aggregator</th>
</tr>
<tr>
<th> Column Name </th>
<th> Function </th>
</tr>
<tr>
<td> <input> </td>
<td> <input> </td>
</tr>
</table>
<input type="button" value="Generate same table from HTML." />
JSfiddle Link : - >https://jsfiddle.net/shreekantbatale2/evqsuxm8/5/
What I understand is that you want to add a template table. Here is a simple way to do it with jQuery
var id = 0;
function generate_table() {
var table = `<table id='table${id}'>
<tr>
<th colspan="2">Aggregator</th>
</tr>
<tr>
<th> Column Name </th>
<th> Function </th>
</tr>
<tr>
<td> <input> </td>
<td> <input> </td>
</tr>
</table>`
$('#table-template').append(table)
id++
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3> TABLE FROM JAVA SCRIPT</h3>
<input type="button" value="Generate a table." onclick="generate_table()" />
<h3> TABLE FROM HTML</h3>
<div id='table-template'></div>
<input type="button" value="Generate same table from HTML." />
I think this is what you are lookign for.
function generate_table() {
var table = $('#table6').clone()
table.find('input').val('')
$('#table-template').append(table)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3> TABLE FROM JAVA SCRIPT</h3>
<input type="button" value="Generate a table." onclick="generate_table()" />
<h3> TABLE FROM HTML</h3>
<table id='table6'>
<tr>
<th colspan="2">Aggregator</th>
</tr>
<tr>
<th> Column Name </th>
<th> Function </th>
</tr>
<tr>
<td> <input> </td>
<td> <input> </td>
</tr>
</table>
<input type="button" value="Generate same table from HTML." />
<div id='table-template'></div>
You could use a <template> element to generate new HTML each time you want a new <table>
const button = document.querySelector('.js-create-table');
const template = document.createElement('template');
template.innerHTML = `
<table>
<tr>
<th colspan="2">Aggregator</th>
</tr>
<tr>
<th> Column Name </th>
<th> Function </th>
</tr>
<tr>
<td> <input> </td>
<td> <input> </td>
</tr>
</table>
`;
function generateTable() {
const table = template.content.cloneNode(true);
document.body.append(table);
}
button.addEventListener('click', generateTable);
<button class="js-create-table">Create table</button>
And if you just want to clone the original table and create a duplicate from it one.
const button = document.querySelector('.js-clone-table');
const table = document.querySelector('.js-table');
function cloneTable() {
const clone = table.cloneNode(true);
document.body.append(clone);
}
button.addEventListener('click', cloneTable);
<button class="js-clone-table">Clone table</button>
<table class="js-table">
<tr>
<th colspan="2">Aggregator</th>
</tr>
<tr>
<th> Column Name </th>
<th> Function </th>
</tr>
<tr>
<td> <input> </td>
<td> <input> </td>
</tr>
</table>
to duplicater a table with everyting inside (or any html element)
const btTableCopy = document.getElementById('bt-table-copy')
, originTable = document.getElementById('table6')
, baseRowTbl = originTable.querySelector('tbody tr')
;
var tableNum = 0
;
btTableCopy.onclick=()=>
{
let newTable = originTable.cloneNode(true)
, newTbody = newTable.querySelector('tbody')
;
newTable.id = `table-copy-${++tableNum}` // there cannot be two identical id values on an HTML page
for(let i=0;i<5;i++) // add 5 new rows
{
newTbody.appendChild(baseRowTbl.cloneNode(true))
}
newTable.querySelectorAll('input').forEach(inp=>inp.value='') // clear all table inputs
document.body.appendChild(newTable)
}
table {
border-collapse: collapse;
margin: 1em;
}
thead {
background-color: lightblue;
}
td, th {
border: solid grey 1px;
padding: 1em;
text-align : center;
}
<table id="table6">
<thead>
<tr>
<th colspan="2">Aggregator</th>
</tr>
<tr>
<th> Column Name </th>
<th> Function </th>
</tr>
</thead>
<tbody>
<tr>
<td> <input> </td>
<td> <input> </td>
</tr>
</tbody>
</table>
<button id="bt-table-copy">copy table with 5 new rows</button>

How to get values to the outside from three functions and update them in real time?

I have a table which lets users to add number of participants for an event. in it I used input type number field to get number of participants. then I calculate how much fee they have to pay for each passenger type. I have 3 passenger types.
My table looks like this,
I use keyup mouseup bind to get the input value by user and multiplied it with fee for one participant.
var totalAdults;
jQuery("#number_adults").bind('keyup mouseup', function () {
var numOfAdults = jQuery("#number_adults").val();
totalAdults = numOfAdults * adultFee;
});
I have 3 of above functions to calculate and real time display how much fee that they have to pay in each passenger type.
Now I need to get the total sum of all three passenger type fees and display/update it in real time to the user, at the end of my table.
I tried making each passenger type total value global and calculating it's sum, but I get an error saying missing semicolon error linked to this MDN article
I'm stuck here. how can I get total value on all three passenger types outside their respective functions and display that value correctly in real time? (when they update number of passengers, total for passenger type is changing, I need to change final total accordingly). please help
Update:
this is the html table that I used. this get repeated another two times for other two passenger types.
var adultFee = 150;
var finalTotal = 0;
jQuery("#number_adults").bind('keyup mouseup', function() {
var numOfAdults = jQuery("#number_adults").val();
totalAdults = numOfAdults * adultFee;
jQuery("#adult_amount").html(totalAdults);
// console.log(totalAdults);
finalTotal = finalTotal + totalAdults;
console.log(finalTotal);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<tr>
<td style="font-weight: 600;">Adult</td>
<td id="adult_price" name="adult_price">150.00</td>
<td>
<input id="number_adults" max="3" min="1" name="number_adults" type="number" value="0" class="form-control">
</td>
<td name="amount">
<p id="adult_amount"></p>
</td>
</tr>
This is how I tried to get the final total, it doesn't display any result
jQuery(document).on('change', '#adult_amount', function() {
finalTotal = finalTotal+totalAdults;
alert(finalTotal);
});
I made a working example for you.
$('.inputs').each(function(){
$(this).on('change keyup', function(){
let sumTotal = 0;
$('.inputs').each(function(){
sumTotal += $(this).val() * +$(this).parent().next().data('price');
});
$('.total').text(`${sumTotal} $`);
});
});
td:nth-child(3),
th:nth-child(3){
text-align:center;
}
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="row justify-content-center">
<div class="col-12">
<table class="table table-hover">
<thead>
<tr>
<th></th>
<th>QTY</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
<tr>
<td>Child</td>
<td><input type="number" class="inputs form-control" value="0" min="0" max="999"></td>
<td class="price" data-price="150">150 $</td>
</tr>
<tr>
<td>Adult</td>
<td><input type="number" class="inputs form-control" value="0" min="0" max="999"></td>
<td class="price" data-price="200">200 $</td>
</tr>
<tr>
<td>Adult Plus</td>
<td><input type="number" class="inputs form-control" value="0" min="0" max="999"></td>
<td class="price" data-price="250">250 $</td>
</tr>
<tr>
<td>Total - </td>
<td></td>
<td class="total">0.00 $</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>
(https://codepen.io/bichiko/pen/JQWomy)
Here is a solution which should do what you need.
Compared to your code, the key changes are:
Use classes instead of IDs to identify the elements within each row. This means you can handle changes to all your fields using the same event handling code. I've given all your quantity fields the .qty class, and then bound the event to that class, so all elements with that class will run the same function.
Within the function, I've stripped out all direct references to fields - instead, to get the price field, and the total field for the relevant type, the code uses the positions of the fields relative to each other in the page, it uses the .parent(), .next(), and .prev() functions to find the total and amount fields which are within the same table row as the altered quantity field (which will always be this inside the event handler), so that it does the calculations on the right fields.
To calculate the final overall total, I've defined a separate function. Again this uses a class selector to identify all the "amount" fields, and add each of those values together to get the total. Since this function is triggered at the end of the event handler, it will always update the grand total whenever one of the quantities is updated.
Other minor changes:
use .on() instead of the deprecated .bind()
jQuery(".qty").on('keyup mouseup', function() {
var tdElement = jQuery(this).parent();
var qty = parseInt(this.value);
var fee = parseFloat(tdElement.prev(".price").text());
var typeTotal = qty * fee;
tdElement.next(".amount").html(typeTotal);
calcFinalTotal();
});
function calcFinalTotal()
{
var finalTotal = 0;
$(".amount").each(function() {
finalTotal += parseFloat($(this).text());
});
$("#total").text(finalTotal);
}
td, th
{
border: solid 1px #cccccc;
padding: 5px;
text-align:left;
}
table {
border-collapse: collapse;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<th>Passenger Type</th>
<th>Price</th>
<th>Quantity</th>
<th>Total</th>
<tr>
<th>Adult</th>
<td class="price">150.00</td>
<td>
<input max="3" min="1" name="number_adults" type="number" value="0" class="form-control qty">
</td>
<td class="amount">0
</td>
</tr>
<tr>
<th>Type 2</th>
<td class="price" id="type3_price">200.00</td>
<td>
<input max="3" min="1" name="number_type" type="number" value="0" class="form-control qty">
</td>
<td class="amount">0
</td>
</tr>
<tr>
<th>Type 3</th>
<td class="price" id="type3_price">200.00</td>
<td>
<input max="3" min="1" name="number_type" type="number" value="0" class="form-control qty">
</td>
<td class="amount">0
</td>
</tr>
<tr>
<th colspan="3">Grand Total</th>
<td id="total"></td>
</tr>
</table>
You can simply loop on every rows on the table and calculate the total sum and also the individual. Here i done by the dynamic method. if the total of each passenger is inserted in a unique input, then you can access from that input. Otherwise please follow the method
$(document).on('keyup mouseup','.qty', function() {
calculate();
});
function calculate(){
var finalTotal = 0;
var old = 0;
var mature = 0;
var adult = 0;
$('.qty').each(function(key,value){
$qty = $(this).val();
$type = $(this).attr('data-type');
$amount = $(this).parent().siblings('.adult_price').html();
$total = Number($qty) * parseFloat($amount);
$(this).parent().siblings('.amount').html($total);
finalTotal += $total;
if($type == 'adult')
adult += parseFloat($total);
else if($type == 'mature')
mature += parseFloat($total);
else if($type == 'old')
old += parseFloat($total);
});
$('.grandTotal').html(finalTotal);
// console.log('Adult',adult);
// console.log('Mature',mature);
// console.log('Old',old);
}
table {
border-collapse: collapse;
width: 80%;
}
th, td {
text-align: left;
padding: 8px;
}
tr:nth-child(even){background-color: #f2f2f2}
th {
background-color: #4CAF50;
color: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>Passenger Types</th>
<th>Amount</th>
<th>Qty</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<tr>
<td><b>Adult</b></td>
<td class="adult_price" name="adult_price">150.00</td>
<td>
<input max="3" min="1" name="number_adults" type="number" value="0" class="form-control qty" data-type="adult">
</td>
<td name="amount" class='amount'></td>
</tr>
<tr>
<td><b>Mature</b></td>
<td class="adult_price" name="adult_price">200.50</td>
<td>
<input max="3" min="1" name="number_adults" type="number" value="0" class="form-control qty" data-type="mature">
</td>
<td name="amount" class='amount'></td>
</tr>
<tr>
<td><b>Old</b></td>
<td class="adult_price" name="adult_price">150.00</td>
<td>
<input max="3" min="1" name="number_adults" type="number" value="0" class="form-control qty" data-type="old">
</td>
<td name="amount" class='amount'></td>
</tr>
<tr>
<td colspan="3"><b>Grand Total</b></td>
<td class='grandTotal'>100</td>
</tr>
</tbody>
</table>
jQuery is very flexible use class instead of id. If you use inputs, selects, etc you should delegate the input or change event to them.
$('input').on('input', function() {...
input event will trigger as soon as user types or selects on or to an input tag. change event will trigger when a user types or selects on or to an input and then clicks (unfocus or blur event) elsewhere.
The HTML is slightly modified for consistency. Note that there are 2 extra inputs per <tr>.
When using input inside tables you can traverse the DOM by first referencing the imputed/changed/clicked tag as $(this) then climb up to the parent <td> and from there either go to the next <td> using .next() or go to the previous <td> using .prev(). Once you get to a neighboring <td> use .find() to get the input within. When extracting a number from an input it is normally a string but with jQuery method .val() it should extract input value as a number automatically. Details commented in demo.
/*
//A - Any tag with the class of .qty that the user inputs data into triggers a function
//B - Get the value of the imputed .qty (ie $(this))
//C - reference $(this) parent <td> go to the next <td> then find a tag with the class .price and get its value
//D - reference $(this) parent <td> go to the previous <td> then find a tag with the class of .total then set its value to the product of qty and price and fix it with hundredths (.00 suffix)
//E - Declare an empty array
//F - Get the value of each .total, convert it into a number then push the number into the empty array
//G - Use .reduce() to get the sum of all values within the array then fix it with hundredths (.00 suffix) and set it as the value of .grand
*/
$('.qty').on('input', function() { //A
var qty = $(this).val(); //B
var price = $(this).parent().prev('td').find('.price').val(); //C
$(this).parent().next('td').find('.total').val((qty * price).toFixed(2)); //D
var totals = []; //E
$('.total').each(function() {
totals.push(Number($(this).val()));
}); //F
$('.grand').val(totals.reduce((sum, cur) => sum + cur).toFixed(2)); //G
});
table {
table-layout: fixed;
}
td {
width: 6ch
}
[readonly] {
border: 0;
width: 6ch;
text-align: right
}
[type=number] {
text-align: right
}
<table>
<tr>
<td style="font-weight: 600;">Adult</td>
<td><input class="price" name='price' value='150.00' readonly></td>
<td>
<input class="qty" name="qty" min="0" max="3" type="number" value="0" class="form-control">
</td>
<td>
<input class="total" name='total' readonly>
</td>
</tr>
<tr>
<td style="font-weight: 600;">Senior</td>
<td><input class="price" name='price' value='100.00' readonly></td>
<td>
<input class="qty" name="qty" min="0" max="3" type="number" value="0" class="form-control">
</td>
<td>
<input class="total" name='total' readonly>
</td>
</tr>
<tr>
<td style="font-weight: 600;">Child</td>
<td><input class="price" name='price' value='75.00' readonly></td>
<td>
<input class="qty" name="qty" min="0" max="3" type="number" value="0">
</td>
<td>
<input class="total" name='total' readonly>
</td>
</tr>
<tr>
<td colspan='3' style='text-align:right;'>Total</td>
<td><input class='grand' name='grand' value='0' readonly></td>
</table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
This is axample of yours problem, try using object
var data = {a:0, b:0, c: 0}
function one (){
data.a = data.a + 10
console.log(data.a)
total()
}
function two (){
data.b = data.b + 10
total()
console.log(data.b)
}
function three () {
data.c = data.c + 30
total()
console.log(data.c)
}
function total () {
var totaly = data.a + data.b + data.c
console.log('Total input :', totaly)
}
<button onclick="one()"> get A </button>
<button onclick="two()"> get B</button>
<button onclick="three()"> get C </button>

How to display a message beside respective input in an html table?

I have created a table inside a form and one column consists of input elements. I have written a JavaScript function to validate each input. If invalid, the corresponding error message should be displayed beside respective input. In my case, for any input, the error message is always displayed beside the first input.
I tried using <div> and <span> tags with respective id values. For every invalid input the error message is displayed beside the first input and not the corresponding input.
Html table
<table>
<tr>
<td>S.No</td>
<td>Particulars</td>
<td>Amount</td>
<td></td>
</tr>
<tr>
<td>01</td>
<td>Annual Rent (Only of residential unit not owned by employer)</td>
<td><input type="number" name="ann_rent"><div id="ar_invalid"></div></td>
</tr>
<tr>
<td>02</td>
<td>Mediclaim (U/s. 80D of I.T. Act)</td>
<td><input type="number" name="medi"><div id="medi_invalid"></div></td>
</tr>
<tr>
<td>03</td>
<td>Interest paid for Home Loan</td>
<td><input type="number" name="home_int"><div id="home_invalid"></div></td>
</tr>
<tr>
<td>04</td>
<td>National Pension</td>
<td><input type="number" name="nat_pen"><div id="pen_invalid"></div></td>
</tr>
</table>
Javascript function
function validate() {
var a,b,c,d;
a = document.getElementsByName("ann_rent")[0].value;
b = document.getElementsByName("medi")[0].value;
c = document.getElementsByName("home_int")[0].value;
d = document.getElementsByName("nat_pen")[0].value;
if(!a || a < 0) {
document.getElementById("ar_invalid").innerHTML = text;
return false;
}
if(!b || b < 0) {
document.getElementById("medi_invalid").innerHTML = text;
return false;
}
if(!c || c < 0) {
document.getElementById("home_invalid").innerHTML = text;
return false;
}
if(!d || d < 0) {
document.getElementById("pen_invalid").innerHTML = text;
return false;
}
}
Table is inside this form
<form action="process_form.php" method="post" onSubmit="return validate();">
CSS
td, th {
text-align: left;
padding: 8px;
}
table {
margin-top: 30px;
margin-bottom: 10px;
font-family: arial, sans-serif;
width: 100%;
}
If user enters a negative value in input name="home_int", then the error message should be displayed beside input home_int. But actually, the error message is getting displayed beside input name="ann_rent". This situation is occurring for every input.
use th for headers. Add a new td for the error message
<table>
<tr>
<th>S.No</th>
<th>Particulars</th>
<th>Amount</th>
<th></th>
</tr>
<tr>
<td>01</td>
<td>Annual Rent (Only of residential unit not owned by employer)</td>
<td><input type="number" name="ann_rent"></td>
<td><div id="ar_invalid"></div></td>
</tr>
</table>
css
table td, table th {
padding: 20px;
border-spacing: 10px;
}
table {
border-collapse: collapse;
}
Assuming you have a button to submit for form validation which goes something like this:
<input type="submit" name="s" value="ds"/>
What happening is when your function gets inside the first if it then returns false and form will not be submitted so the other ifs wont perform any action in this situation so when you type any negative number in the first if, other ifs whether they are positive or negative wont work and the code will execute the message in the first div
but it will work and will show the message in the desired div if you will only put a negative number inside a specific textbox and all before will be positive
Change the "errors" divs to similar as below so you can have a simpler javascript code:
HTML:
<form action="/" method="post" onSubmit="return validate();">
<table>
<tr>
<td>S.No</td>
<td>Particulars</td>
<td>Amount</td>
<td></td>
</tr>
<tr>
<td>01</td>
<td>Annual Rent (Only of residential unit not owned by employer)</td>
<td><input type="number" name="ann_rent"><div id="ann_rent_invalid"></div></td>
</tr>
<tr>
<td>02</td>
<td>Mediclaim (U/s. 80D of I.T. Act)</td>
<td><input type="number" name="medi"><div id="medi_invalid"></div></td>
</tr>
<tr>
<td>03</td>
<td>Interest paid for Home Loan</td>
<td><input type="number" name="home_int"><div id="home_int_invalid"></div></td>
</tr>
<tr>
<td>04</td>
<td>National Pension</td>
<td><input type="number" name="nat_pen"><div id="nat_pen_invalid"></div></td>
</tr>
</table>
<input type="submit" value="Submit">
</form>
and in javascript:
function validate() {
var text = "error";
var required = ["ann_rent", "medi", "home_int", "nat_pen"];
var errors = 0;
required.forEach(function(element) {
var toselect = element + "_invalid";
var reqV = document.getElementsByName(element)[0].value;
if(!reqV || reqV < 0) {
document.getElementById(toselect).innerHTML = text;
errors++;
} else {
document.getElementById(toselect).innerHTML = null;
}
});
if(errors > 0){
return false;
}
}

How to check if all textboxes in a row are filled using jquery

I have 3 textboxes in each row. At least one of the rows should be filled completely. All the textboxes in any of the rows should not be empty. I have tried below code, it's for the first row only.
var filledtextboxes= $(".setup_series_form tr:first input:text").filter(function () {
return $.trim($(this).val()) != '';
}).length;
We want to get the maximum number of non-empty textboxes in any row, TIA.
Loop through all the rows. In each row, get the number of filled boxes. If this is higher than the previous maximum, replace the maximum with this count.
var maxboxes = -1;
var maxrow;
$(".setup_series_form tr").each(function(i) {
var filledtextboxes = $(this).find("input:text").filter(function () {
return $.trim($(this).val()) != '';
}).length;
if (filledtextboxes > maxboxes) {
maxboxes = filledtextboxes;
maxrow = i;
}
});
You are targeting only first tr here $(".setup_series_form tr:first input:text") so you will not get the expected output.
You have to iterate with every row(tr) inside form and then find the count of
text field having not empty values and store in a maxCount variable by comparing it previous tr count.
Here is a working snippet:
$(document).ready(function() {
var maxCountInRow =0;
var rowNumber;
$(".setup_series_form tr").each(function(index){
var filledtextboxes= $(this).find("input:text").filter(function () {
return $.trim($(this).val()) != '';
}).length;
if(filledtextboxes>maxCountInRow){
maxCountInRow=filledtextboxes;
rowNumber=index;
}
});
console.log("Row Number:"+rowNumber+" having maxCount: "+maxCountInRow);
});
.registrant_table{width: 100%;border: 1px solid #ccc;text-align: center;}
.registrant_table tr td{border: 1px solid #ccc;height: 42px;font-weight: bolder;}
.registrant_table input{border: 0px !important;width: 100%;height: 42px;text-align: center;font-weight: normal;}
label.error{color: red !important;}
.err-fields{background-color:red;color: white !important;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="setup_series_form">
<div>
<table class="registrant_table">
<tr class="title">
<td>No</td>
<td>Official Full Name</td>
<td>Mobile Contact</td>
<td>Email</td>
</tr>
<tr class="in-fields">
<td>1</td>
<td><input type="text" value="sas" name="firstname[]"></td>
<td><input type="text" value="" name="phone[]"></td>
<td><input type="text" value="" name="email[]"></td>
</tr>
<tr class="in-fields">
<td>2</td>
<td><input type="text" value="sas" name="firstname[]"></td>
<td><input type="text" value="sas" name="phone[]"></td>
<td><input type="text" name="email[]"></td>
</tr>
<tr class="in-fields">
<td>3</td>
<td><input type="text" name="firstname[]"></td>
<td><input type="text" name="phone[]"></td>
<td><input type="text" name="email[]"></td>
</tr>
</table>
</div>
</form>

Auto calculation in table using jquery

My Requirment:
I have table with quantity cell as editable when change quantity it need to multiply with other parent td value.and sum the column values .
(i.e) if i change quantity to 2 then the parent rows need multiply by 2 & columns get value get added
I done all the calculation part the only thing when i delete or change the quantity the calculated value remain same how to revert back to old values
Here is my fiddle
Fiddle link
$(document).ready(function(){
$('.quantity').on('change, keyup',function(){
var val=$(this).text();
// To avoid auto inc while pressing arrow keys
var preVal =$(this).data('prevval');
<!-- console.log(preVal); -->
if(preVal && preVal == val){
return;
}
$(this).data('prevval',val);
//To avoid auto inc while pressing arrow keys //
if(val =='' || isNaN(val) || val < 1){
return;
}
$(this).siblings().each(function(){
var tbvalue=$(this).text();
var result= parseInt(tbvalue)*parseInt(val);
$(this).text(result);
})
autoSum();
});
autoSum();
});
function autoSum(){
for (var i = 1; i < 8; i++) {
var sum = 0;
$('.auto_sum>tbody>tr>td:nth-child(' + i + ')').each(function() {
sum += parseInt($(this).text()) || 0;
});
// set total in last cell of the column
$('.auto_sum>tbody>tr>td:nth-child(' + i + ')').last().html(sum);
// $('.auto_sum>tbody>tr>td:nth-child(' + i + ')').last().toggleClass('total');
}
}
.total {
background-color: #000;
color: #fff;
font-weight: bold;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div class="container">
<h2>Table calculation</h2>
<p>Calculaton</p>
<table class="auto_sum table table-hover">
<thead>
<tr>
<th>value1</th>
<th>value2</th>
<th>value3</th>
<th>Quantity</th>
</tr>
</thead>
<tbody>
<tr>
<td>10</td>
<td>5</td>
<td>4</td>
<td class="quantity" type="number" contenteditable>1</td>
</tr>
<tr>
<td>8</td>
<td type>2</td>
<td>3</td>
<td class="quantity" type="number" contenteditable>1</td>
</tr>
<tr>
<td>20</td>
<td>3</td>
<td>5</td>
<td class="quantity" type="number" contenteditable>1</td>
</tr>
<tr class="total">
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
</tbody>
</table>
</div>
Inside every row, with the td that store the numbers to be multiplied, keep the original numbers in a data-val attribute in the td, and multiply your content editable value with that. Display the multiplied value as the td text. One change here is that, when you delete the value of contenteditable cell, it takes it as 1 for row calculation, but does not consider it for column multiplication.
HTML part
<div class="container">
<h2>Table calculation</h2>
<p>Calculaton</p>
<table class="auto_sum table table-hover">
<thead>
<tr>
<th>value1</th>
<th>value2</th>
<th>value3</th>
<th>Quantity</th>
</tr>
</thead>
<tbody>
<tr>
<td data-val="10">10</td>
<td data-val="5">5</td>
<td data-val="4">4</td>
<td class="quantity" type="number" contenteditable>1</td>
</tr>
<tr>
<td data-val="8">8</td>
<td data-val="2">2</td>
<td data-val="3">3</td>
<td class="quantity" type="number" contenteditable>1</td>
</tr>
<tr>
<td data-val="20">20</td>
<td data-val="3">3</td>
<td data-val="5">5</td>
<td class="quantity" type="number" contenteditable>1</td>
</tr>
<tr class="total">
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
</tbody>
</table>
</div>
JS Part
$(document).ready(function(){
$('.quantity').on('change, keyup',function(){
var val=$(this).text();
// To avoid auto inc while pressing arrow keys
var preVal =$(this).data('prevval');
$(this).data('prevval',val);
//To avoid auto inc while pressing arrow keys //
if(val =='' || isNaN(val) || val < 1 || val == undefined){
val = 1;
}
$(this).siblings().each(function(){
var tbvalue=$(this).data("val");
var result= parseInt(tbvalue)*parseInt(val);
$(this).text(result);
});
autoSum();
});
autoSum();
});
function autoSum(){
for (var i = 1; i <= 4; i++) {
var sum = 0;
var tdBoxes = $('.auto_sum>tbody>tr>td:nth-child(' + i + ')');
for(var j=0; j<tdBoxes.length-1;j++)
{
var value = $(tdBoxes[j]).text();
//alert(value);
sum += (value == undefined || value == "")? 0 : parseInt(value);
}
// set total in last cell of the column
$('.auto_sum>tbody>tr>td:nth-child(' + i + ')').last().html(sum);
// $('.auto_sum>tbody>tr>td:nth-child(' + i + ')').last().toggleClass('total');
}
}
All details are commented in working demo. I added <form>, <output>, <input type='number'> and <input type='hidden'>. Also I don't remember <td> having a type attribute or a value of number either.
With the combination of the right elements and attributes (and maybe even a little CSS), you don't have to write so much JS/jQ because there many aspects of form functions built within HTML.
Demo
// Reference the <form>
var main = document.forms.main;
// Reference of all of <input> and <output> of <form>
var field = main.elements;
/* Register the input event on the <form>
|| ANY input event triggered within <form> will...
*/
main.addEventListener('input', function(e) {
// Check to see which field is the user inputing into
if (e.target !== e.currentTarget) {
// Reference that field
var input = document.getElementById(e.target.id);
// console.log(input.value);
// Get the row of the field
var row = input.parentNode.parentNode;
// console.log(row);
/* Gather all hidden fields of that row into a NodeList
|| and convert that NodeList into an array.
*/
var rowArray = Array.from(row.querySelectorAll('[type=hidden]'));
// console.log(rowArray);
// On each hidden field, perform the following function...
rowArray.forEach(function(cel, idx) {
// Get the value of hidden field
const base = cel.value;
// Find the <output> that comes after the hidden field
var output = cel.nextElementSibling;
/* Calculate the product of the hidden field's value
|| and the input field's value
*/
var val = parseInt(base, 10) * parseInt(input.value, 10);
// Display the prouct in the <output>
output.value = val;
});
/* Because we registered the input event on the <form>,
|| we have many ways to manipulate the <form>'s fields.
|| In this demo we have been using:
|| HTMLFormElement and HTMLFormControlsCollection interfaces
|| https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement
|| http://www.dyn-web.com/tutorials/forms/references.php#dom0
*/
field.out1.value = Number(field.o1a.value) + Number(field.o1b.value) + Number(field.o1c.value);
field.out2.value = Number(field.o2a.value) + Number(field.o2b.value) + Number(field.o2c.value);
field.out3.value = Number(field.o3a.value) + Number(field.o3b.value) + Number(field.o3c.value);
field.out4.value = Number(field.out1.value) + Number(field.out2.value) + Number(field.out3.value);
}
});
.total {
background-color: #000;
color: #fff;
font-weight: bold;
}
input,
output {
display: inline-block;
font: inherit;
width: 6ch;
border: 0;
text-align: center;
}
.quantity input {
padding-top: .5em;
outline: 0;
}
-
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1, user-scalable=no">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<style>
</style>
</head>
<body>
<div class="container">
<form id='main'>
<table class="auto_sum table table-hover">
<thead>
<caption>
<h2>Table Calculation</h2>
<h3>Quanities</h3>
</caption>
<tr>
<th>Value1</th>
<th>Value2</th>
<th>Value3</th>
<th>Quantity</th>
</tr>
</thead>
<tbody>
<tr id='rowA'>
<td>
<!--[0][1]-->
<input id='v1a' type='hidden' value='10'>
<output id='o1a'>0</output>
</td>
<td>
<!--[2][3]-->
<input id='v2a' type='hidden' value='5'>
<output id='o2a'>0</output>
</td>
<td>
<!--[4][5]-->
<input id='v3a' type='hidden' value='4'>
<output id='o3a'>0</output>
</td>
<td class="quantity">
<!--[6]-->
<input id='qa' type='number' value='0' max='999' min='0'>
</td>
</tr>
<tr id='rowB'>
<td>
<!--[7][8]-->
<input id='v1b' type='hidden' value='8'>
<output id='o1b'>0</output>
</td>
<td>
<!--[9][10]-->
<input id='v2b' type='hidden' value='2'>
<output id='o2b'>0</output>
</td>
<td>
<!--[11][12]-->
<input id='v3b' type='hidden' value='3'>
<output id='o3b'>0</output>
</td>
<td class="quantity">
<!--[13]-->
<input id='qb' type='number' value='0' max='999' min='0'>
</td>
</tr>
<tr id='rowC'>
<td>
<!--[14][15]-->
<input id='v1c' type='hidden' value='20'>
<output id='o1c'>0</output>
</td>
<td>
<!--[16][17]-->
<input id='v2c' type='hidden' value='3'>
<output id='o2c'>0</output>
</td>
<td>
<!--[18][19]-->
<input id='v3c' type='hidden' value='5'>
<output id='o3c'>0</output>
</td>
<td class="quantity">
<!--[20]-->
<input id='qc' type='number' value='0' max='999' min='0'>
</td>
</tr>
<tr class="total">
<td>
<!--[21]-->
<output id='out1' for='o1a o1b o1c'>0</output>
</td>
<td>
<!--[22]-->
<output id='out2' for='o2a o2b o2c'>0</output>
</td>
<td>
<!--[23]-->
<output id='out3' for='o3a o3b o3c'>0</output>
</td>
<td>
<!--[24]-->
<output id='out4' for='out1 out2 out3'>0</output>
</td>
</tr>
</tbody>
</table>
</form>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</body>
</html>

Categories

Resources