I am trying to enable and disable checkboxes based on selection of checkboxes. If you take a look here for a live version of my code
http://jsfiddle.net/prady/VZ4yW/3/
What i want is there cannot be 2 checkboxes selected in the same row and there cannot be 2 checkboxes selected in the same column. Looking at the link might give you a clear understanding of what i wanted.
There can be only one checkbox selected in the column "Change this parameter" and "Generate simulated value for this param" but both cant be of the same row.
Just in case you are not able to view the link here is the code
<table>
<tr>
<td></td>
<td></td>
<td>Change this parameter</td>
<td>Generate simulated value for this param</td>
</tr>
<tr>
<td>Project cost</td>
<td><input type ="text" id ="pc"/></td>
<td><input class="change" type="checkbox" name="chkBox" id="chkBox"></input></td>
<td><input class="sim" type="checkbox" name="chkBox1" id="chkBox1"></input></td>
</tr>
<tr>
<td>Avg hours</td>
<td><input type ="text" id ="avghrs"/></td>
<td><input class="change" type="checkbox" name="chkBoxa" id="chkBoxa"></input></td>
<td><input class="sim" type="checkbox" name="chkBox1a" id="chkBox1a"></input></td>
</tr>
<tr>
<td>Project completion date</td>
<td><input type ="text" id ="cd"/></td>
<td><input class="change" type="checkbox" name="chkBoxb" id="chkBoxb"></input></td>
<td><input class="sim" type="checkbox" name="chkBox1b" id="chkBox1b"></input></td>
</tr>
<tr>
<td>Hourly rate</td>
<td><input type ="text" id ="hr"/></td>
<td><input class="change" type="checkbox" name="chkBoxc" id="chkBoxc"></input></td>
<td><input class="sim" type="checkbox" name="chkBox1c" id="chkBox1c"></input></td>
</tr>
</table>
<script type="text/javascript">
$(document).ready(function(){
$('#chkBox').click(function(){
var paramChangeBoxes = $('input:checkbox.change');
if ($(this).is(':checked')) {
paramChangeBoxes.attr('disabled', 'disabled');
$('#chkBox1').attr('disabled', 'disabled');
$('#chkBox').removeAttr('disabled');
}
else
{
paramChangeBoxes.removeAttr('disabled');
$('#chkBox1').removeAttr('disabled');
}
});
$('#chkBoxa').click(function(){
var paramChangeBoxes = $('input:checkbox.change');
if ($(this).is(':checked')) {
paramChangeBoxes.attr('disabled', 'disabled');
$('#chkBox1a').attr('disabled', 'disabled');
$('#chkBoxa').removeAttr('disabled');
}
else
{
paramChangeBoxes.removeAttr('disabled');
$('#chkBox1a').removeAttr('disabled');
}
});
$('#chkBoxb').click(function(){
var paramChangeBoxes = $('input:checkbox.change');
if ($(this).is(':checked')) {
paramChangeBoxes.attr('disabled', 'disabled');
$('#chkBox1b').attr('disabled', 'disabled');
$('#chkBoxb').removeAttr('disabled');
}
else
{
paramChangeBoxes.removeAttr('disabled');
$('#chkBox1b').removeAttr('disabled');
}
});
$('#chkBoxc').click(function(){
var paramChangeBoxes = $('input:checkbox.change');
if ($(this).is(':checked')) {
paramChangeBoxes.attr('disabled', 'disabled');
$('#chkBox1c').attr('disabled', 'disabled');
$('#chkBoxc').removeAttr('disabled');
}
else
{
paramChangeBoxes.removeAttr('disabled');
$('#chkBox1c').removeAttr('disabled');
}
});
$('#chkBox1').click(function(){
var paramChangeBoxes = $('input:checkbox.sim');
if ($(this).is(':checked')) {
paramChangeBoxes.attr('disabled', 'disabled');
$('#chkBox').attr('disabled', 'disabled');
$('#chkBox1').removeAttr('disabled');
}
else
{
paramChangeBoxes.removeAttr('disabled');
$('#chkBox1').removeAttr('disabled');
$('#chkBox').removeAttr('disabled');
}
});
$('#chkBox1a').click(function(){
var paramChangeBoxes = $('input:checkbox.sim');
if ($(this).is(':checked')) {
paramChangeBoxes.attr('disabled', 'disabled');
$('#chkBoxa').attr('disabled', 'disabled');
$('#chkBox1a').removeAttr('disabled');
}
else
{
paramChangeBoxes.removeAttr('disabled');
$('#chkBox1a').removeAttr('disabled');
$('#chkBoxa').removeAttr('disabled');
}
});
$('#chkBox1b').click(function(){
var paramChangeBoxes = $('input:checkbox.sim');
if ($(this).is(':checked')) {
paramChangeBoxes.attr('disabled', 'disabled');
$('#chkBoxb').attr('disabled', 'disabled');
$('#chkBox1b').removeAttr('disabled');
}
else
{
paramChangeBoxes.removeAttr('disabled');
$('#chkBox1b').removeAttr('disabled');
$('#chkBoxb').removeAttr('disabled');
}
});
$('#chkBox1c').click(function(){
var paramChangeBoxes = $('input:checkbox.sim');
if ($(this).is(':checked')) {
paramChangeBoxes.attr('disabled', 'disabled');
$('#chkBoxc').attr('disabled', 'disabled');
$('#chkBox1c').removeAttr('disabled');
}
else
{
paramChangeBoxes.removeAttr('disabled');
$('#chkBox1c').removeAttr('disabled');
$('#chkBoxc').removeAttr('disabled');
}
});
});
</script>
You need to store busyRows and busyCols and add row and col attr to checkbox;
Update them after each change event and then update disabled attributes.
function getCB_x(elt) { return elt.parentNode.cellIndex; }
function getCB_y(elt) { return elt.parentNode.parentNode.rowIndex; }
$(document).ready(function(){
var busyRows = [], busyCols = [];
var checkboxes = $("table input[type=checkbox]");
// get topleft checkbox
var firstCb = checkboxes[0];
// and calculate its offsets
var colOffset = getCB_x(firstCb);
var rowOffset = getCB_y(firstCb)
// get bottomright checkbox
var lastCb = checkboxes.last()[0];
// calculate offsets and init busy flags
for (var i = getCB_x(lastCb) - colOffset; i >=0; i--) busyCols[i] = false;
for (var i = getCB_y(lastCb) - rowOffset; i >=0; i--) busyRows[i] = false;
// define callback
function updateCB(){
var col = getCB_x(this) - colOffset;
var row = getCB_y(this) - rowOffset;
// set corresponding row and col as "busy"
busyRows[row] = this.checked;
busyCols[col] = this.checked;
// update column with current checkbox
for (var r = 0; r < busyRows.length; r++) {
cb = checkboxes[r*busyCols.length+col];
if ((busyRows[r] || busyCols[col]) && !cb.checked) {
$(cb).attr('disabled', 'disabled');
} else {
$(cb).removeAttr('disabled', 'disabled');
}
}
// update row with current checkbox
for (var c = 0; c < busyCols.length; c++) {
cb = checkboxes[row*busyCols.length+c];
if ((busyRows[row] || busyCols[c]) && !cb.checked) {
$(cb).attr('disabled', 'disabled');
} else {
$(cb).removeAttr('disabled', 'disabled');
}
}
}
// update state for already set items
for (var i = 0; i < checkboxes.length; i++) {
var cb = checkboxes[i];
if (cb.checked) updateCB.call(cb);
}
// assign onlick handler
checkboxes.click(updateCB);
});
This code will work for any regular dense grid of checkboxes. Regular means that every row should have the same amount of checkboxes and every column should have the same amount of checkboxes. Dense means there should be no rows w/o chekcboxes between rows with checkboxes. The same for columns.
If you'll have additional checkboxes in table, which should not be included in grid, add some class to them (e.g. "non-grid") and select only cb's w/o that class:
var checkboxes = $("table input[type=checkbox]:not(.non-grid)");
Related
i have a table that i compare row values using checkbox to see if they are the same, am using a jquery code to compare the table rows that were selected by a checkbox, it works perfectly, now what i want is to be able to exclude two columns from the comparison and compare other columns in the two selected rows
$('.ApprovalForm').submit(function(event) {
event.preventDefault(); // Prevent the form from submitting via the browser
if ($(":checkbox:checked").length < 2 || $(":checkbox:checked").length > 2) {
alert('You have to select two flights');
} else {
var form = $(this);
//get all checkboxes that are selected
var selected = $("input:checked");
//loop through your columns
var x = 0;
for (var i = 1; i <= 17; i++) {
var prev = null;
$.each($(selected), function() {
var curr = $(this).closest("tr").find("td").eq(i).text();
//if at least one value is different highlight the column
if (curr !== prev && prev !== null) {
x++;
console.log(3333);
}
prev = curr;
})
}
console.log(x);
if (x <= 0) {
$("#modal-Approve").modal('show');
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize(),
}).done(function(response) {
$("#MessageStatus ").val(response);
location.reload();
}).fail(function(data) {
// Optionally alert the user of an error here...
alert(data);
});
} else {
alert('Selected flights are not the same, check if they are the same by using detail button');
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th style="display:none">id</th>
<th>Mission</th>
<th>First Pilot</th>
<th>Second Pilot</th>
<th>Aircraft</th>
<th>No</th>
<th style="display:none">TakeOffTime</th>
<th style="display:none">LandingTime</th>
<th style="display:none">Date</th>
</tr>
</thead>
<tbody>
<tr>
<td>test Flying</td>
<td>Juliet</td>
<td>Pascal</td>
<td>boeing 42</td>
<td>255</td>
<td>12:45</td>
<td>14:20</td> <!-- exclude this from the values that will be compared -->
<td>12/1/2020</td> <!-- exclude this too -->
<td> <input type="checkbox" name="FlightId[]"> </td>
</tr>
<tr>
<td>test Flying</td>
<td>Juliet</td>
<td>Pascal</td>
<td>boeing 42</td>
<td>255</td>
<td>12:45</td>
<td>14:30</td> <!-- exclude this from the values that will be compared -->
<td>12/2/2020</td> <!-- exclude this too -->
<td> <input type="checkbox" name="FlightId[]"> </td>
</tr>
</tbody>
</table>
so the idea is to be able to exclude some td values from the comparison
Add 'exc_toggle' class to each th in your header row
Add event listener for clicking these classes to toggle an 'exclude' data attribute
Add a hidden cell to each row in tbody so your column counts are the same between the header and tbody rows
Add to your form submit event listener to iterate over the 'exc_toggle' class and create a to_ignore index for each data-exclude = 1
Skip your comparison when i is found in your ignore index
Code below.
HTML:
<table>
<thead>
<tr id="header_row">
<th style="display:none" class="exc_toggle">id</th>
<th class="exc_toggle">Mission</th>
<th class="exc_toggle">First Pilot</th>
<th class="exc_toggle">Second Pilot</th>
<th class="exc_toggle">Aircraft</th>
<th class="exc_toggle">No</th>
<th class="exc_toggle">TakeOffTime</th>
<th class="exc_toggle">LandingTime</th>
<th class="exc_toggle">Date</th>
</tr>
</thead>
<tbody>
<tr>
<td style="display:none"></td>
<td>test Flying</td>
<td>Juliet</td>
<td>Pascal</td>
<td>boeing 42</td>
<td>255</td>
<td>12:45</td>
<td>14:20</td> <!-- exclude this from the values that will be compared -->
<td>12/1/2020</td> <!-- exclude this too -->
<td> <input type="checkbox" name="FlightId[]"> </td>
</tr>
<tr>
<td style="display:none"></td>
<td>test Flying</td>
<td>Juliet</td>
<td>Pascal</td>
<td>boeing 42</td>
<td>255</td>
<td>12:45</td>
<td>14:30</td> <!-- exclude this from the values that will be compared -->
<td>12/2/2020</td> <!-- exclude this too -->
<td> <input type="checkbox" name="FlightId[]"> </td>
</tr>
</tbody>
</table>
jQuery (in document header):
$(document).on('click', '.exc_toggle', function(){
if($(this).data('exclude') == 1)
{
$(this).data('exclude', 0);
$(this).css('background-color', '');
} else {
$(this).data('exclude', 1);
$(this).css('background-color', '#F00');
}
});
jQuery (modified ApprovalForm submit event):
$('.ApprovalForm').submit(function(event) {
event.preventDefault(); // Prevent the form from submitting via the browser
if ($(":checkbox:checked").length < 2 || $(":checkbox:checked").length > 2) {
alert('You have to select two flights');
} else {
var ignore_indices = [];
var cnt = 0;
$('.exc_toggle').each(function(){
if($(this).data('exclude') == 1)
{ignore_indices.push(cnt);}
cnt++;
});
var form = $(this);
//get all checkboxes that are selected
var selected = $("input:checked");
//loop through your columns
var x = 0;
for (var i = 1; i <= 17; i++) {
if(ignore_indices.indexOf(i) < 0)
{
var prev = null;
$.each($(selected), function() {
var curr = $(this).closest("tr").find("td").eq(i).text();
//if at least one value is different highlight the column
if (curr !== prev && prev !== null) {
x++;
console.log(3333);
}
prev = curr;
})
} else {
prev = null;
}
}
console.log(x);
if (x <= 0) {
$("#modal-Approve").modal('show');
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize(),
}).done(function(response) {
$("#MessageStatus ").val(response);
location.reload();
}).fail(function(data) {
// Optionally alert the user of an error here...
alert(data);
});
} else {
alert('Selected flights are not the same, check if they are the same by using detail button');
}
}
});
To compare duplicate takeoff times, add the class 'takeoff' to each td in your takeoff time column, then add this jQuery:
$(document).on('change', 'input:checkbox', function(){
var takeoff = '';
$('.takeoff').css('background-color', '');
$('input:checked').each(function(){
var td_target = $(this).closest('tr').find('.takeoff');
takeoff = td_target.html();
var matches = $('input:checked').parents('tr').find('.takeoff:contains("'+takeoff+'")');
if(matches.length > 1)
{td_target.css('background-color', '#F00');}
else
{td_target.css('background-color', '');}
});
});
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
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/
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().
I have 5 checkboxes. One of them is the header for all checkboxes. If I check the header checkbox, all should check automatically, and if I uncheck it, all should uncheck. If I uncheck any of the child checkboxes, the header should automatically uncheck.
My code is like this:
<html>
<SCRIPT LANGUAGE="JavaScript">
function checkAll()
{
if(pp_checkall.checked==true)
{
for (i = 1; i <= pp_check.length; i++)
pp_check[i].checked = true ;
}
else
{
for (i = 1; i <= pp_check.length; i++)
pp_check[i].checked = false ;
}
}
</script>
<SCRIPT LANGUAGE="JavaScript">
function checkOne()
{
for (i = 1; i <= pp_check.length; i++)
{
if(pp_check[i].checked==false)
{
pp_checkall.checked = false ;
}
}
}
</script>
<body>
<table>
<tr><th width="1px"><input type="checkbox" text="Dharan" name="pp_checkall" onclick="checkAll();"></th></tr>
<tr>
</tr>
<tr> <input type="checkbox" name="pp_check" value="1" onclick="checkOne();"></tr>
<!--<tr> <input type="checkbox" name="pp_check" value="2" onclick="checkOne();"></tr>
<tr> <input type="checkbox" name="pp_check" value="3" onclick="checkOne();"></tr>
<tr> <input type="checkbox" name="pp_check" value="4" onclick="checkOne();"></tr> -->
</table>
</body>
</html>
Its working fine too, but in some cases only one <td> checkbox will appear, which stops the code from working. Please give some solution to solve this.
Try this
<script type="text/javascript" language="javascript">
var pp_check = document.getElementsByName('pp_check');
var pp_checkall = document.getElementsByName('pp_checkall')[0];
function checkAll() {
if (pp_checkall.checked == true) {
for (i = 0; i < pp_check.length; i++)
pp_check[i].checked = true;
}
else {
for (i = 0; i < pp_check.length; i++)
pp_check[i].checked = false;
}
}
function checkOne() {
var pp_check = document.getElementsByName('pp_check');
for (i = 0; i < pp_check.length; i++) {
if (pp_check[i].checked == false)
pp_checkall.checked = false;
}
}
</script>
You can use jQuery for the same.
$('input[name="pp_checkall"]').change(function () {
$('input[name=pp_check]').attr('checked', this.checked);
});
$('input[name="pp_check"]').change(function () {
$('input[name="pp_checkall"]').prop(
'checked',
$('input[name=pp_check]:not(:checked)').length === 0 ? true : false
);
});
Demo: http://jsfiddle.net/gPeh8/1/