Perform Dynamic Table Calculations in HTML - jQuery? - javascript

I have an HTML table which allows the user to enter some values, either directly or from a select menu.
<form action="" method="">
<table id="scores" width="358" border="1">
<tr>
<th colspan="5">Activities</th>
</tr>
<tr class="header">
<td width="104">Activity</td>
<td width="163">Rating</td>
<td width="69">Hours Per Week</td>
<td width="163">Weeks Per Year</td>
<td width="163">Average Hours Per Week</td>
</tr>
<tr>
<td class="title"><input type="text" value=""/></td>
<td><select name="rating">
<option value=""></option>
<option value="High">High</option>
<option value="Moderate">Moderate</option>
</select></td>
<td class="title"><input type="text" value=""/></td>
<td class="title"><input type="text" value=""/></td>
<td> </td>
</tr>
<tr>
<td class="title"><input type="text" value=""/></td>
<td><select name="rating">
<option value=""></option>
<option value="High">High</option>
<option value="Moderate">Moderate</option>
</select></td>
<td class="title"><input type="text" value=""/></td>
<td class="title"><input type="text" value=""/></td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td class="title">Total High</td>
<td class="title" id="totalHigh"></td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td class="title">Total Moderate</td>
<td class="title" id="totalModerate"></td>
</tr>
<tr>
<td colspan="5"><button class="copy" value="Set Value">Submit</button></td>
</tr>
</table>
I need to perform a couple of calculations as follows:
for each row I need to calculate the "Average Hours Per Week" which is simply the (Hours Per Week * Weeks Per Year)/52
for each row the user can select either "High" or "Moderate" for the Rating. I need to then calculate the total of the "Average Hours Per Week" for all rows where Rating = "High" and all rows where Rating = "Moderate".
I've spent the better part of today pulling out my last remaining hairs trying to get something working using jQuery which I'm a newbie with. I've setup a jsfiddle at:
http://jsfiddle.net/tZPDr/
which has a simplified version of the table. Would greatly appreciate any help about how to go about performing these 2 calculations dynamically as the user types.
Many thanks,
Steve

Did a few tweaks, check out this fiddle. Rest you should be able to figure it out. :)

If you want to do this as user types, you need to bind onto keypress or keydown.
Example:
$('td.hours input').on('keypress', function() {
//get the values and calculate
});
Then choose you fields and perform the calculations. You can get the values like this
Example:
var hrs = $('td.hours input').val();

Related

How do I get my select and two checkboxes to filter my table to show only all matching data javascript?

I have a table with a bunch of states and it has two columns that display whether the event is family friendly and/or Spanish speaking. I have a dropdown selector with states listed and two checkboxes that should filter the matching rows that are family friendly and/or Spanish speaking.
My current dropdown filters out states to show only the state selected. My two checkboxes individually filter the rows to display those that are family friendly or Spanish speaking. When both checkboxes are checked it shows family friendly or Spanish Speaking. I would like it to show family friendly AND Spanish speaking making all other rows disappear that don't match disappear. My checkboxes are currently taking the state dropdown into consideration too and I would like that to stay the same.
For example, if you select Texas, in my table, and check both dropdowns I would like only events that have Texas listed as state, are family friendly and Spanish speaking (should only return one result).
My code:
<script>
$("input[name='filterStatus'], #filter").change(function() {
var classes = [];
var filterValue = $("#filter").val();
var row = $('.row-events');
$("input[name='filterStatus']").each(function() {
if ($(this).is(":checked")) {
classes.push('.' + $(this).val());
}
});
row.hide();
row.each(function(i, el) {
if ((classes == "" || classes.some(function(className) {
return $(el).find('td' + className).html() != ` `;
})) && (filterValue == "all" || $(el).attr('data-type') == filterValue))
{
$(el).show();
}
});
});
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label id='label-state-text'>Select Your State:</label>
<select class="state" id="filter">
<option value="all" selected="selected">Select a State</option>
<option value="AZ">Arizona</option>
<option value="CA">California</option>
<option value="NC">North Carolina</option>
<option value="SC">South Carolina</option>
<option value="TX">Texas</option>
</select>
</form>
<form name="FilterForm" id="FilterForm" action="" method="">
<input type="checkbox" name="filterStatus" value="family" />
<label for="filter_1">Family Friendly?</label>
<input type="checkbox" name="filterStatus" value="ESP" />
<label for="filter_2">Spanish Speaking?</label>
</form>
<table id="myTable-events">
<thead>
<tr>
<th class='event_heading'> Name </th>
<th class='event_heading'> Date </th>
<th class='event_heading'> State </th>
<th class='event_heading'> Family Friendly </th>
<th class='event_heading'> Spanish Speaking </th>
</tr>
</thead>
<tr class="row-events" data-type="TX">
<td> Event 1 </td>
<td> 10/22/2023 </td>
<td> Texas </td>
<td class="family"> Yes </td>
<td class="ESP"> </td>
</tr>
<tr class="row-events" data-type="CA">
<td> Event 11 </td>
<td> 10/22/2023 </td>
<td> California </td>
<td class="family"> Yes </td>
<td class="ESP"> </td>
</tr>
<tr class="row-events" data-type="TX">
<td> Event 2 </td>
<td> 09/20/2023 </td>
<td> Texas </td>
<td class="family"> </td>
<td class="ESP"> Yes </td>
</tr>
<tr class="row-events" data-type="NC">
<td> Event 3 </td>
<td> 06/18/2023 </td>
<td> North Carolina </td>
<td class="family"> </td>
<td class="ESP"> </td>
</tr>
<tr class="row-events" data-type="SC">
<td> Event 4 </td>
<td> 05/02/2023 </td>
<td> South Carolina </td>
<td class="family"> </td>
<td class="ESP">Yes</td>
</tr>
<tr class="row-events" data-type="TX">
<td> Event 5 </td>
<td> 12/29/2023 </td>
<td> Texas </td>
<td class="family"> Yes </td>
<td class="ESP"> Yes </td>
</tr>
<tr class="row-events" data-type="CA">
<td> Event 6 </td>
<td> 11/20/2023 </td>
<td> California </td>
<td class="family"> </td>
<td class="ESP"> Yes </td>
</tr>
<tr class="row-events" data-type="AZ">
<td> Event 7 </td>
<td> 08/09/2023 </td>
<td> Arizona </td>
<td class="family"> </td>
<td class="ESP"> </td>
</tr>
<tr class="row-events" data-type="TX">
<td> Event 8 </td>
<td> 10/19/2023 </td>
<td> Texas </td>
<td class="family"> </td>
<td class="ESP"> Yes </td>
</tr>
<tr class="row-events" data-type="CA">
<td> Event 9 </td>
<td> 08/04/2023 </td>
<td> California </td>
<td class="family"> Yes </td>
<td class="ESP"> Yes </td>
</tr>
<tr class="row-events" data-type="AK">
<td> Event 10 </td>
<td> 03/26/2023 </td>
<td> Alaska </td>
<td class="family"> Yes </td>
<td class="ESP"> Yes </td>
</tr>
</table>

Cannot hide fields and populate field based on selection

I am trying to:
1. Hide and display fields based on SELECT a field
2. Populate a field based on check boxes
However neither is working. Both were based on working solutions from others. The only difference I can think of is that I am using TABLE to format them. But I don't know if that makes a difference.
The HTML code:
<form method="POST">
<table cellspacing="2" cellpadding="2">
<tr>
<td valign="top" /><b>Business:</b>
<td><select id="business" name="business" >
<option value="1">Sell</option>
<option value="2">Buy</option>
<option value="3">Both</option>
<option value="4">Trade</option>
<option value="5">Freight</option>
<option value="6">Customs</option>
</select>
</td>
</tr>
<div id="freight">
<tr>
<td><b>Service Type:</b></td>
<td><select name="type">
<option value="1">Air Cargo</option>
<option value="2">Couriers</option>
<option value="3">Freight Forwarder</option>
</select>
</td>
</tr>
<tr>
<td><b>Tollfree Number:</b></td>
<td><input type="text" name="tollfree" />
</td>
</tr>
</div>
<tr>
<td valign="top"><b>Your Email Address:</b></td>
<td><input type="text" name="email" /></td>
</tr>
<div id="customs">
<tr>
<td /><b>Services:</b>
<td>
<input type="checkbox" value="ACA - Air Cargo Agent" />ACA - Air Cargo Agent<br />
<input type="checkbox" value="AFF - Air Freight Forwarder" />AFF - Air Freight Forwarder<br />
</td>
</tr>
</div>
<tr>
<td><b>Products/Services:</b></td>
<td><input type="text" name="products" /></td>
</tr>
<div id="brand">
<tr>
<td><b>Brand Names:</b></td>
<td><input type="text" name="brands" /></td>
</tr>
</div>
</table>
</form>
The jQuery code for doing these:
$(':checkbox').click(function() {
$('input[name=products]').val(
$(':checkbox:checked').map(function() {
return $(this).val();
}).get().join(',')
);
});
$(document).ready(function () {
toggleFields();
$("#business").change(function () {
toggleFields();
});
});
function toggleFields() {
if ($("#business").val() == 1 || ($("#business").val() == 2 || ($("#business").val() == 3)
$("#brand").show();
$("#freight").hide();
$("#customs").hide();
else
if ($("#business").val() == 5)
$("#brand").hide();
$("#freight").show();
$("#customs").show();
else
if ($("#business").val() == 6)
$("#brand").hide();
$("#freight").hide();
$("#customs").show();
else
$("#brand").hide();
$("#freight").hide();
$("#customs").hide();
}
For example when you select "Sell", "Buy" or "Both" (in Business), the SERVICE TYPE and TOLLFREE NUMBER fields are supposed to be hidden, as well as SERVICES field. They are wrapped in DIV id "freight" and "customs" and supposed to be invisible. But they are not. All fields are shown regardless.
Second problem is if you select Customs (in Business) the Services field which is composed of checkboxes is supposed to be shown and when click on the check boxes, the value in these checkboxes is supposed to populate the Products/Services field. It is not doing that either.
Here is the jsfiddle for this code:
http://jsfiddle.net/5SArB/571/
which is based on the working version of both
jsfiddle.net/5SArB/ (toggle fields based on form values)
and
jsfiddle.net/dTrVt/ (populate input field based on checkbox id values)
I am pulling my hair on this and just can't understand why it is not working. Any help is appreciated. Thank you in advance.
There are several issues with the code, the first of which is that the javascript is poorly formed.
You can't write if statements without curly braces if they take more than one line
The first if statement in toggleFields is missing some parentheses
Once you get that fixed, the other problem concerns the formation of your html table. Don't wrap the table rows with divs, since that's improper html table structure. Instead, you might take out the divs, and assign the "id"s to the table rows instead. Essentially what you would be doing then is showing/hiding table rows rather than showing/hiding divs containing the table rows.
The resulting HTML would be then:
<tr id="freight">
...
</tr>
Rather than:
<div id="freight">
<tr>
...
</tr>
</div>
Here's a fiddle with the proposed changes.
Hope that helps!
Edit: In case somebody comes across this in the future, the problem was a simple issue with load order -- the document wasn't ready when the click event was bound. The solution is as simple as moving the click event inside the document.ready callback.
As already mentioned, you have syntax errors and you can't have div as a child of table.
In the if...else if statements you are missing the block definitions...
Also assign the ids to the tr instead of nesting it in a div.
Also the code can be simplified as
$(':checkbox').click(function () {
$('input[name=products]').val($(':checkbox:checked').map(function () {
return $(this).val();
}).get().join(','));
});
jQuery(function ($) {
$("#business").change(toggleFields).change();
});
function toggleFields() {
var el = $('#business option:selected').data('el'),
els = el ? '#'+el.split(/,\s*/).join(', #'):'';
var $els =els? $(els).show():$();
$('.bussiness-field').not($els).hide()
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h1>Toggle fields based on form values</h1>
<form method="POST">
<table cellspacing="2" cellpadding="2">
<tr>
<td valign="top" /><b>Business:</b>
<td>
<select id="business" name="business">
<option value="1" data-el="brand">Sell</option>
<option value="2" data-el="brand">Buy</option>
<option value="3" data-el="brand">Both</option>
<option value="4">Trade</option>
<option value="5" data-el="freight, customs">Freight</option>
<option value="6" data-el="customs">Customs</option>
</select>
</td>
</tr>
<tr id="freight" class="bussiness-field">
<td><b>Service Type:</b>
</td>
<td>
<select name="type">
<option value="1">Air Cargo</option>
<option value="2">Couriers</option>
<option value="3">Freight Forwarder</option>
</select>
</td>
</tr>
<tr>
<td><b>Tollfree Number:</b>
</td>
<td>
<input type="text" name="tollfree" />
</td>
</tr>
<tr>
<td valign="top"><b>Your Email Address:</b>
</td>
<td>
<input type="text" name="email" />
</td>
</tr>
<tr id="customs" class="bussiness-field">
<td /><b>Services:</b>
<td>
<input type="checkbox" value="ACA - Air Cargo Agent" />ACA - Air Cargo Agent
<br />
<input type="checkbox" value="AFF - Air Freight Forwarder" />AFF - Air Freight Forwarder
<br />
</td>
</tr>
<tr>
<td><b>Products/Services:</b>
</td>
<td>
<input type="text" name="products" size="40" />
</td>
</tr>
<tr id="brand" class="bussiness-field">
<td><b>Brand Names:</b>
</td>
<td>
<input type="text" name="brands" />
</td>
</tr>
</table>
</form>

How to reorder table rows using Jquery or Javascript

I have a table similar to the following:
Level
$1,000
$500
$100
Other Amount
The HTML is generated by a web based program that allows you to enter your desired values but does not provide an option to re-order them.
The values are ordered highest to lowest but I need them to be lowest to highest.
Here is the HTML that produced the table:
<table width="100%" id="TablePledgeLevelInner">
<tbody>
<tr>
<td width="1%"> </td>
<td>Level<br>
</td>
</tr>
<tr>
<td nowrap="">
<input type="radio" id="Radio1" onclick="SetAmount(form, 1000);" value="764853" name="PledgeLevelID">
</td>
<td>$1,000 <br>
</td>
</tr>
<tr>
<td nowrap="">
<input type="radio" id="Radio1" onclick="SetAmount(form, 500);" value="764915" name="PledgeLevelID">
</td>
<td>$500 <br>
</td>
</tr>
<tr>
<td nowrap="">
<input type="radio" id="Radio1" onclick="SetAmount(form, 100);" value="764921" name="PledgeLevelID">
</td>
<td>$100 <br>
</td>
</tr>
<tr>
<td nowrap="">
<input type="radio" id="Radio1" onclick="SetAmount(form, 0);" value="764922" name="PledgeLevelID">
</td>
<td>Other Amount <br>
</td>
</tr>
</tbody>
</table>
How would I reorder this table using Jquery or Javascript?
Thanks in advance. Any help is greatly appreciated.
Use jQuery DataTables. It'll let you sort the output and provide loads of other nice functionality out of the box.

how to dynamically calculate value in the text box

i have a invoice where i have to calculate some value in the textbox using jquery.
I don't know much about Jquery. Please help me to solve this problem.
In my invoice there is quantity textbox,
if users enters the quantity then dynamically it should show the
calculated price i.e (total_subPrice= unit_price * quantity) in
another textbox called "price".
And again the total sum of all the price should be visible in the button as a Total.
please check my below html code and run it in browser then you will understand my problem exactly.
<html>
<body>
<form name="invoice form" action="saveToDatabase.java">
<table border="1" height="30%" width="30%">
<tr>
<td align="center" colspan="5">Customer Invoice</td>
</tr>
<tr>
<td width="5%" bgcolor="#CCCCCC">Sn.no.</td>
<td width="25%" bgcolor="#CCCCCC">Item</td>
<td width="25%" bgcolor="#CCCCCC">Unit Price(In $)</td>
<td width="20%" bgcolor="#CCCCCC">Quantity</td>
<td width="25%" bgcolor="#CCCCCC">Line Total<br/>(Price * Qnty)</td>
</tr>
<tr>
<td width="5%">1</td>
<td width="25%">Iphone 5S</td>
<td width="25%"><input type="text" value="400" name="unitprice1" size="4" disabled></td>
<td width="20%"><input type="text" name="quantity1" value="2" size="2"/></td>
<td width="25%"><input type="text" name="price1" value="400" size="4"/></td>
</tr>
<tr>
<td width="5%">2</td>
<td width="25%">Ipad 2</td>
<td width="25%"><input type="text" value="700" name="unitprice2" size="4" disabled></td>
<td width="20%"><input type="text" name="quantity2" value="1" size="2"/></td>
<td width="25%"><input type="text" name="price2=" value="700" size="4"/></td>
</tr>
<tr>
<td width="5%">1</td>
<td width="25%">mp3</td>
<td width="25%"><input type="text" value="50" name="unitprice1" size="4" disabled></td>
<td width="20%"><input type="text" name="quantity1" value="3" size="2"/></td>
<td width="25%"><input type="text" name="price1" value="150" size="4"/></td>
</tr>
<tr>
<td align="right" colspan="5">Total<input type="text" name="subtotal" value="1250" size="12" disabled/></td>
</tr>
</table>
</form></body>
</html>
I enjoy seeing practical examples to learn stuff like jQuery myself, so I made an example for your problem so you can see how it works: http://jsfiddle.net/bozdoz/LGyeq/
Line by line:
Select all of the input tags and call a function if they are changed:
$('input').change(function(){
create a variable to store the totals, to calculate the subtotal:
var linetotals = 0;
select each element with class 'lineTotal' (which I added, so that we could select them):
$('.lineTotal').each(function(){
Get price and quantity by finding the input elements within the same tr element (eq(#) gets the first and second element respectively):
price = $(this).parents('tr').find('input').eq(0).val();
quantity = $(this).parents('tr').find('input').eq(1).val();
Set the lineTotal class element to the new total, and add the total to lineTotals variable:
$(this).val(price*quantity);
linetotals += price*quantity;
});
Set the subtotal to the value of the linetotals variable:
$('#total').val(linetotals);
});​
This is one way you can do it. It has a lot to do with preference. Hope this is a good start.
Update
Re: Askers new request for more generalized code
Use CSS Attribute selectors to select the input fields. JSFiddle is updated with the following code:
$('input').change(function(){
var linetotals = 0;
$('[name^="price"]').each(function(){
price = $(this).parents('tr').find('input').eq(0).val();
quantity = $(this).parents('tr').find('input').eq(1).val();
$(this).val(price*quantity);
linetotals += price*quantity;
});
$('[name=subtotal]').val(linetotals);
});​

select specific input element in a specific row and column

Cosider this image:
How I can select it without it's ID with jQuery? I mean how I can select it like this statement:
Find Input in Row with Code=1000 and Column Desc2
thanks
Edit 1)
HTML Code
<table border="1" width="300px">
<tr>
<td>
Desc2
</td>
<td>
Desc1
</td>
<td>
Code
</td>
</tr>
<tr>
<td bgcolor="#CCCCB3">
<input id="Text1" type="text" />
</td>
<td>
</td>
<td>
1000
</td>
</tr>
<tr>
<td bgcolor="#FFFFCC">
</td>
<td bgcolor="#FFFFCC">
</td>
<td bgcolor="#FFFFCC">
</td>
</tr>
<tr>
<td bgcolor="#CCCCB3">
<input id="Text2" type="text" />
</td>
<td>
</td>
<td>
1001
</td>
<tr>
<td bgcolor="#CCCCB3" class="style1">
<input id="Text3" type="text" />
</td>
<td class="style1">
</td>
<td class="style1">
1002
</td>
</tr>
<tr>
<td bgcolor="#CCCCB3">
<input id="Text4" type="text" />
</td>
<td>
</td>
<td>
1003
</td>
</tr>
</table>
Select the last cell, filter the row whose last cell has a value which is equal to "1000", and select the first input element of the collection:
$("table td:last-of-type").filter(function(){
return $(this).text() == "1000";
}).parent().find("input:first");
For constructing such selectors, you can use the following:
:eq() and .eq()
:nth-child() (for a specific child position only!)
Warning: Do not fall in the trap of contains(). This method select all elements which contain the given phrase. .contains(1000) will also select <td>10000</td>.

Categories

Resources