jQuery dynamic select data from prepared html table - javascript

I have some problem with dynamic select data from html table.
I give example of table and input, but in fact the table consists of hundreds rows.
<select name="options">
<option value="equal">=</option>
<option value="notequal">!=</option>
<option value="more">></option>
<option value="less"><</option>
</select>
<input type="input" value="input numbers" id="filter">
<table border="1">
<tr>
<td width="150">NAME</td>
<td class="wys">Value</td>
<td>Value2</td>
<td>Value3</td>
</tr>
<tr>
<td width="150">Name1</td>
<td class="wys">65</td>
<td>87</td>
<td>988</td>
</tr>...
So, question is how to hide/show row depending on input data and selected option, assuming that input data refer to column Value
My first solution was:
$("#filter").keyup(function() {
var filter = $("#filter").val();
var options = $("#options").val();
if(options == 'equal'){
$("table td.wys:contains('" + $(this).val() + "')").parent().show();
$("table td.wys:not(:contains('" + $(this).val() + "'))").parent().hide();
}
else if(options == 'notequal'){
$("table td.wys:contains('" + $(this).val() + "')").parent().hide();
$("table td.wys:not(:contains('" + $(this).val() + "'))").parent().show();
}
else if(options == 'more'){
//HOW TO SHOW/HIDE ROW GREATER THAN eg. 100
}
else {
//HOW TO SHOW/HIDE ROW SMALLER THAN eg. 100
}
});
So I found second solution...
var wys = $("table td.wys");
wys.each(function() {
$(this).attr('data-wys', parseInt($(this).text()));
});
I set attributes and parse to int all values from column VALUE
Someone could tell me how to SHOW/HIDE row from table if I select equal, not equal, more or less and press my numer...?

You can use the .filter() method:
// A helper object for doing some math
var operators = {
'equal': function(a, b) { return a == b },
'notequal': function(a, b) { return a != b },
'more': function(a, b) { return a > b },
'less': function(a, b) { return a < b }
};
var $tr = $('tr').not(':first'),
$sel = $("select[name='options']").on('change', function() {
// Trigger the keyup on the select's change event
$("#filter").keyup();
});
$("#filter").keyup(function () {
var v = $.trim(this.value),
o = $sel.val();
// Show all the TRs when the value's length is 0
if (!v.length) return $tr.show();
$tr.hide().filter(function () {
var t = $('.wys', this).text();
return operators[o](t, v);
}).show();
});
http://jsfiddle.net/q2PVm/1/

Related

How can I display the sum of certain columns of a table in javascript?

I do not understand javascript at all, I study as needed and I need help
I need to sum up the values of certain columns of a table, the rows of which are marked with a checkbox
For example: I mark the checkbox in two rows of the table and the sum of 3,4 and 5 columns is summed up and displayed somewhere on the page
Now I managed to find a piece of code that summarizes the value of the checked checkboxes in the form, and displays it on the page
I need help in replacing the part that receives the "value" of the input, with the one that gets the values of the cells in the stob = head of the table and sums them
Here is this code
var
$form = $("#out_form"),
$allCheckboxes = $("input:checkbox", $form),
$sumOut = $("#checked-sum"),
$countOut = $("#checked-count");
$allCheckboxes.change(function() {
var
sum = 0,
count = 0;
$allCheckboxes.each(function(index, el) {
var
$el = $(el),
val;
if ($el.is(":checked")) {
count++;
val = parseFloat($el.val());
if (!isNaN(val)) {
sum += val;
}
}
});
$sumOut.text(sum);
$countOut.text(count);
});
HTML
<form action="" method="post" id="out_form">
<input type="hidden" name="next" value="{{next}}"/>
<button type="submit">Check</button>
<span id="checked-sum">0</span>
<span id="checked-count">0</span>
{%csrf_token%}
<div class="table-view__container">
<table class="table-view__table">
<tbody class="table-view__body">
{% for out in filter.qs %}
<tr>
<td>
<label class="custom_Label">
<input type="checkbox" name="checked" value="{{ out.id }}">
<span class="checkmark"></span>
</label>
</td>
<td>{{out.date|date:"d(D).m.Y"}}</td>
<td>{{out.ts}}</td>
<td>{{out.pl}}</td>
<td>{{out.rem}}</td>
<td>{{out.comment}}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</form>
It is necessary to sum these 3 columns:
...
<td>{{out.ts}}</td>
<td>{{out.pl}}</td>
<td>{{out.rem}}</td>
...
UPD:
I managed to display the amount with the checkbox active, but only the first line:
var
$form = $("#out_form"),
$table = $(".table-view"),
$allCheckboxes = $("input:checkbox", $form),
$sumOut = $("#checked-sum"),
$countOut = $("#checked-count");
$allCheckboxes.change(function() {
var
sum = 0,
count = 0;
$allCheckboxes.each(function(index, el) {
var
$el = $(el),
val;
if ($el.is(":checked")) {
count++;
$form.each(function () {
var val1 = parseInt(document.querySelector(".ts", this).innerHTML,10);
var val2 = parseInt(document.querySelector(".pl", this).innerHTML,10);
var val3 = parseInt(document.querySelector(".rem", this).innerHTML,10);
var total = (val1 * 1) + (val2 * 1) + (val3 * 1);
sum += total;
});
if (!isNaN(val)) {
sum += total;
}
}
});
$sumOut.text(sum);
$countOut.text(count);
});
JavaScript can be confusing, its definitely not an easy programming language. Sorry for not using your code, but I think its overcomplicating things.
So mainly what this code does is to trigger a function using event handlers on all checkboxes, that sums or substracts from the result variable depending if they are checked or unchecked and then show the result in a <span> tag.
Some key points
I used document.querySelectorAll('input[type=checkbox]') to get all the checkbox elements.
The following code is to create one event handler for each checkbox element:
boxes.forEach((box) => {
box.addEventListener("change", function() {
The input checkbox element lives inside a <td></td>, so this.closest('td').nextElementSibling is necessary to get the parent tag and then with the help of nextElementSibling we can get the next <td> element of the table which has the value we need to sum or substract.
Snippet
var boxes = document.querySelectorAll('input[type=checkbox]'),
show = document.getElementById('showResult'), result = 0;
boxes.forEach((box) => {
box.addEventListener("change", function() {
var firstElement = this.closest('td').nextElementSibling,
secondElement = firstElement.nextElementSibling,
firstValue = parseInt(firstElement.innerHTML),
secondValue = parseInt(secondElement.innerHTML);
var sum = firstValue + secondValue;
this.checked ? result += sum : result -= sum;
show.innerHTML = result;
});
});
td {
border: 1px solid #dddddd;
text-align: left;
width:50px;
text-align:center;
}
span{
font-size:20px;
}
<table id="table">
<tr>
<td><input type="checkbox" id="box1" /></td>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td><input type="checkbox" id="box2" /></td>
<td>3</td>
<td>4</td>
</tr>
</table>
<br>
<br>
<span>Result: </span><span id="showResult">0</span>

jQuery filter table includes <select> <option> cell

I am new to jQuery.
I have a table which contains <select><option> tag in a cell like below.
<html>
<input type="text" id="searchInput">
<table border=1>
<thead>
<th>ID</th><th>Name</th><th>position</th>
</thead>
<tbody id="fbody">
<tr>
<td>1</td>
<td>A</td>
<td><select>
<option selected>front</option>
<option>center</option>
<option>back</option>
</select>
</td>
</tr>
<tr>
<td>2</td>
<td>B</td>
<td><select>
<option>front</option>
<option selected>center</option>
<option>back</option>
</select>
</td>
</tr>
</tbody>
</table>
</html>
I found a jQuery code like below and I am trying to filter above table. But it won't work good on <select><option> cell. I would like to know how I can make code work to filter to get selected value.
What I want to do is, when I type "center" in the input box, then show only second row.
<script>
$("#searchInput").keyup(function () {
console.log("value=%o", this.value);
//split the current value of searchInput
var data = this.value.split(" ");
//create a jquery object of the rows
var jo = $("#fbody").find("tr")
//hide all the rows
.hide();
//Recusively filter the jquery object to get results.
jo.filter(function (i, v) {
var $t = $(this);
for (var d = 0; d < data.length; ++d) {
if ($t.is(":contains('" + data[d] + "')")) {
console.log(data[d]);
return true;
}
}
return false;
})
//show the rows that match.
.show();
}).focus(function () {
this.value = "";
$(this).css({
"color": "black"
});
$(this).unbind('focus');
}).css({
"color": "#C0C0C0"
});
</script>
can you try changing your filter condition to
jo.each(function () {
$( this ).find( "td select option:selected" ).each( function(){
for (var d = 0; d < data.length; ++d)
{
if ( $( this ).text() == data[d] )
{
console.log(data[d]);
$( this ).parent("tr").show();
break;
}
}
})
});
or even simply
$("#fbody").find("option:selected").each(function () {
if ( data.indexOf( $( this ).text() ) != -1 ) //updated this line
{
$( this ).parent().parent().parent().show();
}
});
if you want to compare part of the value in TDs to the value entered in textboxes
$( data ).each( function ( index, valueArr ){
if ( value.indexOf( valueArr ) != -1 )
{
$td.parent().show();
}
} );
try to use :selected
if ($t.find('> select > option').is(":selected:contains('" + data[d] + "')")) {

On Select change Disable option if selected previois and create a clone row not working

I am trying to disable a select option if selected on a previous row say my html table creates a row if the value of a last rows text box are filled and select is changed what i was trying to do was if the select option is selected before then on new row created the select option should be disabled when i add the code of disable then the new row is not created.
Demo Fiddle with select code
Demo Fiddle with out select code
$('#results').append('<table width="100%" border="1" cellspacing="0" cellpadding="5" id="productanddates" class="border"> <tr><td> <input type="text" name="to1" id="to1" value="" /> </td> <td> <select class="dd" name="Phonenumberdd1" id="Phonenumberdd1"> <option value="test">test </option><option value="test1">test1 </option><option value="test2">test 2</option></select></td> <td> <input type="text" name="renewal_by1" id="renewal_by1" /> </td> <td> <input type="text" name="Renivaul_to1" id="Renivaul_to1" value="" /> </td></TR></TABLE>');
//*******the select code if this is removed all works fine******?//
setTimeout(function () {
var $selects = $('select');
$selects.on('change', function () {
$("option", $selects).prop("disabled", false);
$selects.each(function () {
var $select = $(this),
$options = $selects.not($select).find('option'),
selectedText = $select.children('option:selected').text();
$options.each(function () {
if ($(this).text() == selectedText) $(this).prop("disabled", true);
});
});
});
$selects.eq(0).trigger('change');
}, 99);
$('#results').on('focus', ':input', function () {
$(this).closest('tr').filter(function () {
return !$(this).data('saved');
})
.find(':input').each(function () {
$(this).data('value', this.value);
$(this).closest('tr').data('saved', true);
});
})
.on('input change', ':input', function () {
$(this).data('filled', this.value != $(this).data('value'))
var tr = $(this).closest('tr');
all = tr.find(':input'),
fld = all.filter(function () {
return $(this).data('filled');
});
if (all.length == fld.length) {
if (!tr.data('done')) {
$('#buttonclck')[0].click();
tr.data('done', true);
}
} else {
if (tr.data('done')) {
tr.next('tr').remove();
tr.data('done', false);
}
}
});
$('#buttonclck').on('click', function () {
var lastRow = $('#productanddates').closest('#productanddates').find("tr:last-child");
var cloned = lastRow.clone();
cloned.find('input, select').each(function () {
var id = $(this).attr('id');
var regIdMatch = /^(.+)(\d+)$/;
var aIdParts = id.match(regIdMatch);
var newId = aIdParts[1] + (parseInt(aIdParts[2], 10) + 1);
$(this).attr('id', newId);
$(this).attr('name', newId);
});
cloned.find("input[type='text']").val('');
cloned.insertAfter(lastRow);
});
$('#results').on('change', '.dd', function (e) {
var data = "dummy data";
$(this).closest('td').prev().find('input').val(data).trigger('input');
$(this).closest('td').next().find('input').val(data).trigger('input');
});
The following code, executed once a new row is added, should iterate through the previous rows and disable in the new row values of select that have already been used:
var prevRows = cloned.siblings();
cloned.find('select option').each(function(index,option) {
prevRows.each(function(i,tr) {
option.value !== $('select', tr).val() || $(option).prop('disabled', true);
});
});
DEMOS
DEMO 1
DEMO 2
DEMO 3

How to filter Table row with multiple condition .ie on checkbox selection show respected row. each checkbox represent Column and row value

I have a table with some dynamic data, and columns as Name,Location, Salary. Problem i am facing in Step 2 i.e multiple condition check. Heres the step by step code.
JS Fiddle Demo
Step 1-
Auto generate Filters i.e dynamically add Checkboxes, depend on table row values
autoFilterItem("filterDiv");
Above function generate dynamic checkboxes, logic is it loop over table, read values row by row and return unique value array and generate checkbox respectively, currently am doing for 2 cols having class loc,sal.
Step 2-
Checkbox change event, depend on status (checked/unchekced) table rows will be hide/show .
The problem i am facing is, if user checked 100 ( class as sal), and Kerala ( class as loc) is unchecked then row having kerala should be hide.
For hide and show am adding/removing class .hideRow
///STEP TWO
// On any checkbox clicked returns desired out
$("body").on('change', '.chk', function () {
var arrObj = [],
arrCheckedValueCLass = [];
var objCheckedData = {};
$("#filterDiv .chk").each(function (index, val) {
var sf = $(this);
if (sf.is(":checked")) {
var sf = $(this);
arrObj.push({
dataValue: $(sf).attr('data-value'),
dataClass: $(sf).attr('data-class')
});
}
});
var self = $(this);
var getClassName = self.attr("data-class");
var matchTextValue = $.trim(self.attr("data-value"));
if (self.is(":checked")) {
if (matchTextValue == "All") {
$(".chk").prop('checked', true);
}
$("." + getClassName).each(function () {
var innerSelf = $(this);
var gVal = $.trim(innerSelf.html());
if (matchTextValue == "All") {
innerSelf.closest("tr").removeClass("hideRow");
} else {
if (matchTextValue === gVal) {
console.log("checked and matchTextValue");
var i = 0,
lg = arrObj.length;
var flagSet = false;
for (i; i < lg; ++i) {
var objValue = arrObj[i].dataValue;
var objClass = arrObj[i].dataClass;
if (getClassName != objClass) {
var prevDataCheck = $.trim(innerSelf.closest("tr").find("." + objClass).html());
if (prevDataCheck == objValue) {
flagSet = true;
return true;
}
}
}
if (!flagSet) {
innerSelf.closest("tr").removeClass("hideRow");
innerSelf.closest("tr").addClass(getClassName + "_X");
}
}
}
});
} else {
if (matchTextValue == "All") {
$(".chk").prop('checked', false);
}
$("." + getClassName).each(function () {
var innerSelf = $(this);
var gVal = $.trim(innerSelf.html());
if (matchTextValue === gVal) {
innerSelf.closest("tr").addClass("hideRow");
innerSelf.closest("tr").removeClass(getClassName + "_X");
}
});
}
});
<div id="filterDiv"></div>
<button>Click</button>
<br>
<div id="tableContainer">
<table id="myTable">
<thead>
<tr>
<th data-name='name'>Name</th>
<th data-loc='Location'>Location</th>
<th data-sal='salary'>Salary</th>
<th data-sts='Active'>Active</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name">James</td>
<td class="loc">Mumbai</td>
<td class="sal">500</td>
<td class="sts">Yes</td>
</tr>
<tr>
<td class="name">Joseph</td>
<td class="loc">Kerala</td>
<td class="sal">100</td>
<td class="sts">No</td>
</tr>
<tr>
<td class="name">Jack</td>
<td class="loc">Delhi</td>
<td class="sal">500</td>
<td class="sts">Yes</td>
</tr>
<tr>
<td class="name">Andrea</td>
<td class="loc">Mumbai</td>
<td class="sal">1000</td>
<td class="sts">No</td>
</tr>
<tr>
<td class="name">David</td>
<td class="loc">Delhi</td>
<td class="sal">100</td>
<td class="sts">No</td>
</tr>
<tr>
<td class="name">David</td>
<td class="loc">Delhi</td>
<td class="sal">99900</td>
<td class="sts">No</td>
</tr>
</tbody>
</table>
</div>
I have created the fiddle from the things that you noted and able to produce the result( that is, if user checked 100 ( class as sal), and Kerala ( class as loc) is unchecked then row having kerala should be hide.)
I do not how efficient the solution is.There may be more efficient way to acheive that but anyway below is the js code.
$(document).ready(function () {
//STEP ONE STARTS
// This function generate checkbox from table data, which will be used for filteration
autoFilterItem("filterDiv");
function autoFilterItem(idOfHolderDiv) {
$("#" + idOfHolderDiv).empty();
var arr1 = [];
$(".sal").each(function () {
arr1.push($.trim($(this).html()));
});
var arrNew = unique(arr1).sort(function (a, b) {
return a - b
});
$.each(arrNew, function (i, val) {
$("<input/>", {
"type": "checkbox",
"class": "chk",
"data-class": "sal",
"data-value": val,
"id": "chk" + val,
"checked": "checked"
}).appendTo("#" + idOfHolderDiv).wrap("<div></div>").after(val);
});
$("#" + idOfHolderDiv).append("<hr>");
var arr2 = [];
$(".loc").each(function () {
arr2.push($.trim($(this).html()));
});
var arr2New = unique(arr2).sort();
$.each(arr2New, function (i, val) {
$("<input/>", {
"type": "checkbox",
"class": "chk",
"data-class": "loc",
"data-value": val,
"id": "chk" + val,
"checked": "checked"
}).appendTo("#" + idOfHolderDiv).wrap("<div></div>").after(val);
});
$("#" + idOfHolderDiv).append("<hr>");
function unique(array) {
return $.grep(array, function (el, index) {
return index == $.inArray(el, array);
});
}
}
// STEP ONE ENDS
///STEP TWO
// On any checkbox clicked returns desired out
var selectedSalaryArr = [];
var selectedLocationArr = [];
$("body").on('change', '.chk', function () {
var selectedVal = $(this).attr('data-value');
$('#filterDiv div').each(function () {
var checkedval = $(this).find('input.chk').attr('data-value');
var isChecked = $(this).find('input.chk').is(':checked');
var dataClass = $(this).find('input.chk').attr('data-class');
if (selectedVal === checkedval) {
if (dataClass === 'sal') {
var isExists = $.inArray(checkedval, selectedSalaryArr);
if (isExists === -1) {
selectedSalaryArr.push(checkedval);
} else {
selectedSalaryArr.splice($.inArray(checkedval, selectedSalaryArr), 1);
}
} else {
var isExists = $.inArray(checkedval, selectedLocationArr);
if (isExists === -1) {
selectedLocationArr.push(checkedval);
} else {
selectedLocationArr.splice($.inArray(checkedval, selectedLocationArr), 1);
}
}
}
});
$('#myTable tbody tr').each(function () {
var currentSalary = $(this).find('.sal').text();
var currentLocation = $(this).find('.loc').text();
var matchedSalaryValueExists = $.inArray(currentSalary, selectedSalaryArr);
var matchedLocationValueExists = $.inArray(currentLocation, selectedLocationArr);
if (selectedSalaryArr.length > 0 && selectedLocationArr.length > 0) {
if (matchedSalaryValueExists !== -1 && matchedLocationValueExists !== -1) {
if (!($(this).hasClass('hiderow'))) {
$(this).addClass('hiderow');
}
} else {
if ($(this).hasClass('hiderow')) {
$(this).removeClass('hiderow');
$(this).show();
}
}
}
else {
if (matchedSalaryValueExists !== -1 || matchedLocationValueExists !== -1) {
if (!($(this).hasClass('hiderow'))) {
$(this).addClass('hiderow');
}
} else {
if ($(this).hasClass('hiderow')) {
$(this).removeClass('hiderow');
$(this).show();
}
}
}
});
$('#myTable tbody tr.hiderow').hide();
});
});
Below is the jsfiddle link:
https://jsfiddle.net/shrawanlakhe/v8gyde77/

JQuery Set Odd, Even of Total

I have a table that sum Columns and Rows, and shows the result of the sum.
I have to change the color of each total. If is even, put it "green". If it is odd put it "red"
This is my table:
<table id="sum_table">
<tr>
<td><input value="0" class="sum1" /></td>
<td><input value="0" class="sum2"/></td>
<td><input value="0" class="sum3"/></td>
<td class="total">0</td>
</tr>
<tr>
<td><input value="0" class="sum1"/></td>
<td><input value="0" class="sum2"/></td>
<td><input value="0" class="sum3"/></td>
<td class="total">0</td>
</tr>
<tr>
<td><input value="0" class="sum1"/></td>
<td><input value="0" class="sum2"/></td>
<td><input value="0" class="sum3"/></td>
<td class="total">0</td>
</tr>
<tr class ="totalCol">
<td>0</td>
<td>0</td>
<td>0</td>
</tr>
</table>
<button id="tabla">+</button>
JQuery:
//Sumamos las columnas
$(document).on('keyup change','#sum_table tr:not(.totalCol) input:text',function() {
var $table = $(this).closest('table');
var total = 0;
var thisNumber = $(this).attr('class').match(/(\d+)/)[1];
$table.find('tr:not(.totalCol) .sum'+thisNumber).each(function() {
total += parseInt(this.value);
});
$table.find('.totalCol td:nth-child('+thisNumber+')').html(total);
});
//AƱadimos filas y coumnas cuando se clica al boton "+".
$("#tabla").click(function () {
$("#sum_table tr:last-child").before("<tr>"+$("#sum_table tr:eq(0)").html()+"</tr>");
$("tr:not(:last-child)").each(function () {
var classname = $(this).find("td:last-child").index() + 1;
$(this).find("td:last-child").before('<td><input class="sum' + classname + '" type="text" value="0"></td>');
});
$("#sum_table tr:last-child").append("<td>0</td>");
});
//Creamos la funcion newSum para hacer la suma y mostrarlo en el total.
$(document).on('keyup','input',newSum);
function newSum() {
var sum = 0;
var thisRow = $(this).closest('tr');
var total = 0;
$(thisRow).find("td:not(.total) input").each(function () {
sum += parseInt(this.value);
});
$(thisRow).find(".total").html(sum);
$('.total').each(function () {
total += parseInt($(this).html());
});
}
DEMO JSFIDDLE
Try this, put this code below in newSum() function
if ((this.value % 2 == 0)) {
$(this).css('color', 'green');
} else {
$(this).css('color', 'red');
}
DEMO
I have updated your fiddle please check.
$(document).on('keyup change','#sum_table tr:not(.totalCol) input:text',function() {
var $table = $(this).closest('table');
var total = 0;
var thisNumber = $(this).attr('class').match(/(\d+)/)[1];
$table.find('tr:not(.totalCol) .sum'+thisNumber).each(function() {
total += parseInt(this.value);
});
var total_field = $table.find('.totalCol td:nth-child('+thisNumber+')');
total_field.html(total);
if(total % 2 == true) {
total_field.css("background","red");
}
else {
total_field.css("background","green");
}
});
try this way
JQUERY CODE:
if (total % 2 == 0)
$table.find('.totalCol td:nth-child(' + thisNumber + ')').css('color', 'green'); //set green to even total
else
$table.find('.totalCol td:nth-child(' + thisNumber + ')').css('color', 'red'); //set red to odd total
LIVE DEMO:
http://jsfiddle.net/hdhZZ/7/
Happy Coding :)
Each time one of the inputs is changed, check to see if the total value is an odd or even number...
This is rough, I would toggle a class rather than edit the inline css..
$('td input').on('change', function(){
$('.totalCol td').each(function(){
var $total = parseInt($(this).html());
if ($total !==0 && $total % 2 === 0) {
$(this).css('background-color','green');
}
else {
$(this).css('background-color','#fff');
}
});
});
I realise you've already accepted an answer, but I'd suggest rewriting your approach to the following (though the colouring approach is the same as suggested by the the other answers):
function sumTotals(){
// caching variables:
var table = $('#sum_table'),
inputRows = table.find('tr:not(.totalCol)'),
inputCells = inputRows.find('td:not(.total)');
// iterating over each of the 'td' elements in the '.totalCol' row:
$('.totalCol td').each(function(i,e){
/* i is the index of the current element over which we're iterating
among the collection returned by the selector,
e is the element (the 'this'), which we're not using here.
We're using ':nth-child()' to look at the 'input' elements from
each column, and creating an array of the values using 'map()'
and 'get()': */
var sum = inputRows.find('td:nth-child(' + (i + 1) + ') input').map(function(){
return parseFloat(this.value) || 0;
}).get().reduce(function (prev, curr) {
/* 'reduce()' allows us to perform a calculation (summation) of the
values in the returned array: */
return prev + curr;
});
// setting the text of the current 'td' to the sum,
// using CSS to set the color to either green (even) or red (odd):
$(this).text(sum).css('color', sum % 2 === 0 ? 'green' : 'red');
});
/* iterating over each of the rows with inputs, finding the
last 'td', and updating its text: */
inputRows.find('td:last-child').text(function(){
// caching:
var $this = $(this),
/* getting all the previous 'td' elements, and their 'input'
descendant elements, mapping their values: */
sum = $this.prevAll('td').find('input').map(function(){
return parseFloat(this.value) || 0;
}).get().reduce(function (prev, curr) {
return prev + curr;
});
// setting the color (as above):
$this.css('color', sum % 2 === 0 ? 'green' : 'red');
return sum;
});
}
$('#sum_table').on('keyup change input paste', 'tr:not(.totalCol) input', sumTotals);
JS Fiddle demo.
References:
CSS:
:last-child.
:nth-child().
JavaScript:
Array.prototype.reduce().
parseFloat().
jQuery:
css().
find().
get().
map().
on().
prevAll().
text().

Categories