Dynamic table if checkbox is unchekd empty() the td cell with JS - javascript

I have dynamic table that in one td passes php vales of prices and on end of the table is sum of those prices. There is also a checkbox in every row default checked. I need to empty the content of row where checkbox is unchecked so it removes that price value out of sum calculation.
Question, will that even remove that value? I know setting the td field to hide does not.
Value cell:
<td style="width:10%" class="rowDataSd" id="value">
<?php echo
str_replace(array(".", ",",), array("", "."), $row['rad_iznos']);
?>
</td>
Checkbox cell:
<td style="width:3%">
<input class="w3-check" type="checkbox" checked="checked" id="remove" name="uvrsti" value="<?php echo $row['rad_id']?>">
</td>
I tried with this but nothing happens with no errors:
$(document).ready(function(){
if($("#remove").is(':checked')) {
$("#value").show();
} else {
$("#value").empty();
}
});
I can pass the unique values into each checkbox and value element into id's like:
id="<?php echo $row['rad_id']?>"
. So they tie each other but don't know how to say in JS to empty those elements.
I was also thinking something along the lines of, if on some row checkbox is unchecked empty closest td with id="value". My guess is that would be best solution but I don't know how to write it.
Or even if checkbox is unchecked remove css class .rowDataSd to closest td with id="vale" based on whom calculation is made.
Sum script:
var totals=[0,0,0];
$(document).ready(function(){
var $dataRows=$("#sum_table tr:not('.totalColumn, .titlerow')");
$dataRows.each(function() {
$(this).find('.rowDataSd').each(function(i){
totals[i]+=parseFloat( $(this).html());
});
});
$("#sum_table td.totalCol").each(function(i){
$(this).html('<span style="font-weight: bold;text-shadow: 0.5px 0 #888888;">'+totals[i].toFixed(2)+' kn</span>');
});
});
As seen on picture need to remove row out of calculation if checkbox is unchecked. Keep in mind I dont want to delete to row, just remove it our of calculation.
Any help with how to approach this is appreciated.

Here is a basic example.
$(function() {
function getPrice(row) {
var txt = $(".price", row).text().slice(1);
var p = parseFloat(txt);
return p;
}
function calcSum(t) {
var result = 0.00;
$("tbody tr", t).each(function(i, r) {
if ($("input", r).is(":checked")) {
result += getPrice(r);
}
});
return result;
}
function updateSum(tbl) {
var t = calcSum(tbl);
$("tfoot .total.price", tbl).html("$" + t.toFixed(2));
}
updateSum($("#price-list"));
$("#price-list input").change(function() {
updateSum($("#price-list"));
});
});
#price-list {
width: 240px;
}
#price-list thead th {
width: 33%;
border-bottom: 1px solid #ccc;
}
#price-list tfoot td {
border-top: 1px solid #ccc;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="price-list">
<thead>
<tr>
<th>Name</th>
<th>Price</th>
<th> </th>
</tr>
</thead>
<tbody>
<tr>
<td class="item name">Item 1</td>
<td class="item price">$3.00</td>
<td><input type="checkbox" checked /></td>
</tr>
<tr>
<td class="item name">Item 2</td>
<td class="item price">$4.00</td>
<td><input type="checkbox" checked /></td>
</tr>
<tr>
<td class="item name">Item 3</td>
<td class="item price">$5.00</td>
<td><input type="checkbox" checked /></td>
</tr>
</tbody>
<tfoot>
<tr>
<td>Sum</td>
<td class="total price">$0.00</td>
<td> </td>
</tr>
</tfoot>
</table>

It all boils down to setting up an event handler for the checkboxes. The event handler should perform the following:
Track the checkbox change event for all checkboxes and the DOM ready event
Calculate the total of all rows with checkbox checked
Set the total to the total element
It call also perform any desired changes on the unchecked row .. not done in sample code below
THE CODE
$(function() {
$('.select').on('change', function() {
let total = $('.select:checked').map(function() {
return +$(this).parent().prev().text();
})
.get()
.reduce(function(sum, price) {
return sum + price;
});
$('#total').text( total );
})
.change();//trigger the change event on DOM ready
});
THE SNIPPET
$(function() {
$('.select').on('change', function() {
let total = $('.select:checked').map(function() {
return +$(this).parent().prev().text();
})
.get()
.reduce(function(sum, price) {
return sum + price;
});
$('#total').text( total );
})
.change();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>Item</th>
<th>Price</th>
<th>Select</th>
</tr>
</thead>
<tbody>
<tr>
<td>Item 1</td>
<td>1000</td>
<td><input type="checkbox" class="select" checked></td>
</tr>
<tr>
<td>Item 2</td>
<td>1200</td>
<td><input type="checkbox" class="select" checked></td>
</tr>
<tr>
<td>Item 3</td>
<td>800</td>
<td><input type="checkbox" class="select" checked></td>
</tr>
<tr>
<td>Item 4</td>
<td>102000</td>
<td><input type="checkbox" class="select" checked></td>
</tr>
</tbody>
</table>
<span>TOTAL</span><span id="total"></span>

Related

Why does my checkbox change-handling select or deselect all rows in every table instead of just the current one?

I have multiple tables on a page. Each table, has a "check all" checkbox in the header. In the body, there is another checkbox for each row.
When the user checks each boy row, then a active class is applied and highlights the marked row, and the counter increases/decreases.
I have a problem with the check all function.
When the user selects the check all checkbox in the header, then it should select all the rows in just that one table. I can only get it to check all the rows across all the tables. Also the counter counts all the rows across all the tables, rather than just that one table.
Where am I going wrong?
Here is my code:
// https://gomakethings.com/a-vanilla-js-foreach-helper-method/
var forEach = function forEach(arr, callback) {
Array.prototype.forEach.call(arr, callback);
};
var tableInputs = document.querySelectorAll('.table tbody td .form-check-input');
var tableSelectAll = document.querySelectorAll('.table thead th .form-check-input');
var count = document.querySelector('.output span')
forEach(tableInputs, function(element) {
element.addEventListener('change', function() {
// active class to make row blue
if (element.checked) {
element.parentNode.parentNode.classList.add('active');
} else {
element.parentNode.parentNode.classList.remove('active');
}
// set count to -
var numberSelected = 0;
// count number of checked
for (var i = 0; i < tableInputs.length; i++) {
if (tableInputs[i].checked == true) {
numberSelected++;
}
}
// display the count
count.innerHTML = numberSelected;
});
});
forEach(tableSelectAll, function(element) {
element.addEventListener('change', function() {
if (element.checked == true) {
forEach(tableInputs, function(input) {
input.parentNode.parentNode.classList.add('active');
input.checked = true;
// set count to -
var numberSelected = 0;
// count number of checked
for (var i = 0; i < tableInputs.length; i++) {
if (tableInputs[i].checked == true) {
numberSelected++;
}
}
// display the count
count.innerHTML = numberSelected;
});
} else {
forEach(tableInputs, function(input) {
input.parentNode.parentNode.classList.remove('active');
input.checked = false;
count.innerHTML = 0;
});
}
});
});
.form-check-input {
border: solid 1px #000;
position: relative;
}
tr.active {
background-color: lightblue;
}
body { margin: 0; zoom: .88; }
p { margin: 0; }
<div class="container">
<div class="row">
<div class="col-12">
<p>Table 1</p>
<table class="table table-sm table-borderless">
<thead>
<tr>
<th><input class="form-check-input" type="checkbox" value=""></th>
<th>Request date</th>
<th>Name</th>
<th>Organisation/Employer</th>
<th>Selected Course(s)</th>
</tr>
</thead>
<tbody>
<tr>
<td><input class="form-check-input" type="checkbox" value=""></td>
<td>10/10/2014</td>
<td>Clark Kent</td>
<td><span>Daily Planet</span></td>
<td><span>Flight</span></td>
</tr>
<tr>
<td><input class="form-check-input" type="checkbox" value=""></td>
<td>10/10/2014</td>
<td>Hal Jordan</td>
<td><span>Green Lantern Corps</span></td>
<td>Lighting</td>
</tr>
<tr>
<td><input class="form-check-input" type="checkbox" value=""></td>
<td>10/10/2014</td>
<td>Arthur Curry</td>
<td><span>Atlantis Water</span></td>
<td>Aquatics</td>
</tr>
</tbody>
</table>
<p>Table 2</p>
<table class="table table-sm table-borderless ">
<thead>
<tr>
<th><input class="form-check-input" type="checkbox" value=""></th>
<th>Request date</th>
<th>Name</th>
<th>Organisation/Employer</th>
<th>Selected Course(s)</th>
</tr>
</thead>
<tbody>
<tr>
<td><input class="form-check-input" type="checkbox" value=""></td>
<td>10/10/2014</td>
<td>Barry Allen</td>
<td><span>Star Labs</span></td>
<td><span>Speed</span></td>
</tr>
<tr>
<td><input class="form-check-input" type="checkbox" value=""></td>
<td>10/10/2014</td>
<td>Bruce Wayne</td>
<td><span>Wayne Enterprises</span></td>
<td>Combat</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<p class="output">Total selected: <span>0</span></p>
Regardless of the approach one always should break down the problem into specific tasks which for the OP's requirements are ...
initialize a checkbox related change handling.
on any checkbox' state change do update all checkbox depended states.
do update the checkbox counter at init time and at checkbox state change time.
for any (initially) checked checkbox update its related table row state as well.
The techniques/tools are Event Delegation and the Selectors API
At any checkbox state change the handler inspects the event target whether it belongs to the current table's header or body.
Based on this check one either, for the first case, needs to check/uncheck all of a current table's body-related checkboxes or, according to the second case, one needs to update the state of the sole header-related checkbox.
Updating the checkbox counter is achieved by the correct selector and the queried node list's length value.
function updateCheckboxCounter() {
document
.querySelector('.output > span')
.textContent = document
.querySelectorAll('table.table tbody [type="checkbox"]:checked')
.length;
}
function updateTableRowActiveState(checkboxNode) {
checkboxNode
.closest('tr')
.classList
.toggle('active', checkboxNode.checked);
}
function updateCheckboxDependedStates({ target }) {
const tableNode = target.closest('table.table');
if (target.matches('thead [type="checkbox"]')) {
tableNode
.querySelectorAll('tbody [type="checkbox"]')
.forEach(elmNode => {
elmNode.checked = target.checked;
updateTableRowActiveState(elmNode);
});
} else if (target.matches('tbody [type="checkbox"]')) {
tableNode
.querySelector('thead [type="checkbox"]')
.checked = Array
.from(
target
.closest('tbody')
.querySelectorAll('[type="checkbox"]')
)
.every(elmNode => elmNode.checked);
updateTableRowActiveState(target);
}
updateCheckboxCounter();
}
function init() {
document
.querySelectorAll('table.table')
.forEach(elmNode =>
elmNode.addEventListener('change', updateCheckboxDependedStates)
);
document
.querySelectorAll('table.table tbody [type="checkbox"]:checked')
.forEach(updateTableRowActiveState);
updateCheckboxCounter();
}
init();
.form-check-input {
border: solid 1px #000;
position: relative;
}
tr.active {
background-color: lightblue;
}
body { margin: 0; zoom: .88; }
p { margin: 0; }
<div class="container">
<div class="row">
<div class="col-12">
<p>Table 1</p>
<table class="table table-sm table-borderless">
<thead>
<tr>
<th><input class="form-check-input" type="checkbox" value=""></th>
<th>Request date</th>
<th>Name</th>
<th>Organisation/Employer</th>
<th>Selected Course(s)</th>
</tr>
</thead>
<tbody>
<tr>
<td><input class="form-check-input" type="checkbox" value=""></td>
<td>10/10/2014</td>
<td>Clark Kent</td>
<td><span>Daily Planet</span></td>
<td><span>Flight</span></td>
</tr>
<tr>
<td><input class="form-check-input" type="checkbox" value=""></td>
<td>10/10/2014</td>
<td>Hal Jordan</td>
<td><span>Green Lantern Corps</span></td>
<td>Lighting</td>
</tr>
<tr>
<td><input class="form-check-input" type="checkbox" value="" checked></td>
<td>10/10/2014</td>
<td>Arthur Curry</td>
<td><span>Atlantis Water</span></td>
<td>Aquatics</td>
</tr>
</tbody>
</table>
<p>Table 2</p>
<table class="table table-sm table-borderless ">
<thead>
<tr>
<th><input class="form-check-input" type="checkbox" value=""></th>
<th>Request date</th>
<th>Name</th>
<th>Organisation/Employer</th>
<th>Selected Course(s)</th>
</tr>
</thead>
<tbody>
<tr>
<td><input class="form-check-input" type="checkbox" value="" checked></td>
<td>10/10/2014</td>
<td>Barry Allen</td>
<td><span>Star Labs</span></td>
<td><span>Speed</span></td>
</tr>
<tr>
<td><input class="form-check-input" type="checkbox" value=""></td>
<td>10/10/2014</td>
<td>Bruce Wayne</td>
<td><span>Wayne Enterprises</span></td>
<td>Combat</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<p class="output">Total selected: <span>0</span></p>

Wrong Result Calculate value with checkbox use Jquery

Now im doing some Calculate Checkbox Value Using JQuery and PHP code. The mechanism is, when User checked the checkbox, it will sum the price. I implemented a formula for JQuery but the result it not correct. here is my code
JQUERY
<script>
$(function() {
$('.dealprice').on('input', function(){
const getItemPrice = $(this).closest("tr").find('input[name=itemprice]').val();
var eachPrice = 0;
$('.dealprice:checkbox:checked').each(function(){
eachPrice += isNaN(parseInt(getItemPrice)) ? 0 : parseInt(getItemPrice);
});
$("#totalDeal").text(eachPrice.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,'));
});
});
</script>
for more detail. i made a sample on this site https://repl.it/#ferdinandgush/Sum-Calculate-checkbox just click "run" button and you can able to test it. i need to display correct calculate following that table format
Please help.
You just have to define getItemPrice inside the loop, otherwise you are calculating it only once for the item that was clicked, instead of doing it for every item.
$(function() {
$('.dealprice').on('input', function(){
var eachPrice = 0;
$('.dealprice:checkbox:checked').each(function(){
const getItemPrice = $(this).closest("tr").find('input[name=itemprice]').val();
eachPrice += isNaN(parseInt(getItemPrice)) ? 0 : parseInt(getItemPrice);
});
$("#totalDeal").text(eachPrice.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,'));
});
});
<table class="tg">
<thead>
<tr>
<th class="tg-qh0q">Item</th>
<th class="tg-qh0q">Price</th>
<th class="tg-qh0q">Deal</th>
</tr>
</thead>
<tbody>
<tr>
<td class="tg-0lax">Book</td>
<td class="tg-0lax">$ 10 <input type="hidden" name="itemprice" value="10"></td>
<td class="tg-0lax"><input type="checkbox" class="dealprice" name="deal[12][0]"></td>
</tr>
<tr>
<td class="tg-0lax">Pencil</td>
<td class="tg-0lax">$ 5 <input type="hidden" name="itemprice" value="5"></td>
<td class="tg-0lax"><input type="checkbox" class="dealprice" name="deal[12][1]"></td>
</tr>
<tr>
<td class="tg-0lax">Pen</td>
<td class="tg-0lax">$ 8 <input type="hidden" name="itemprice" value="8"></td>
<td class="tg-0lax"><input type="checkbox" class="dealprice" name="deal[12][2]"></td>
</tr>
<tr>
<td class="tg-amwm" colspan="2">Total</td>
<td class="tg-0lax"><span id="totalDeal">0</span></td>
</tr>
</tbody>
</table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
You have to put the getItemPrice inside of the function of where you get its checked. Please check the following code:
$(function() {
$('.dealprice').on('input', function(){
var eachPrice = 0;
$('.dealprice:checkbox:checked').each(function(){
const getItemPrice = $(this).closest("tr").find('input[name=itemprice]').val();
eachPrice += isNaN(parseInt(getItemPrice)) ? 0 : parseInt(getItemPrice);
});
$("#totalDeal").text(eachPrice.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,'));
});
});
Also check this repl https://repl.it/repls/LavenderAgonizingRoot

Duplicate all Column Cell Input Values with first Column Cell input value

I have an html table that is wrapped by a form with each cell having an input element in it.
I was wondering if there is a way to obtain the first cell's input value of a particular column and pasting that value in the rest of the cells in that column. In other words, the user will type into the input field of first cell and then click on button to duplicate that entry into the rest of the cells of that column.
Assuming you have a table with a button on each row, give the button a class so that it can have an event assigned:
<button type='button' class='copybtn'>copy</button>
don't use IDs as you need multiple buttons;
$(".copybtn").click(function() {
You can get the button's column using var col = $(this).closest("td").index() (add 1 as .index() is 0-based, but we need 1-based :nth-child).
Get the column cells using:
var cells = $("table").find("tr > td:nth-child(" + col + ")");
Various ways to handle this - eg get all the cells as above, then get the first for the input and last for the button or get the input from the first row's nth-child (as in the snippet)
To get the value: var val = inp.val()
To copy the values, depends on your HTML, you could give each destination cell a class then:
cells.find("td.dest").text(val);
or you can get all cells and exclude first/last:
tbl.find("tr:not(:first):not(:last) > td:nth-child(" + col + ")").text(val);
Altogether:
$(".copybtn").click(function() {
// get 0-based column index
var col = $(this).closest("td").index() + 1;
var tbl = $(this).closest("table");
var val = tbl.find("tr:first td:nth-child(" + col + ")").find("input").val();
tbl.find("tr:not(:first):not(:last) > td:nth-child(" + col + ")").text(val);
});
input {
width: 50px;
}
td {
min-width: 20px;
border: 1px solid #CCC;
margin: 0;
padding: 5px
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id='t'>
<tbody>
<tr>
<td><input type='text' class='inp' /></td>
<td><input type='text' class='inp' /></td>
<td><input type='text' class='inp' /></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td><button type='button' class='copybtn'>copy</button></td>
<td><button type='button' class='copybtn'>copy</button></td>
<td><button type='button' class='copybtn'>copy</button></td>
</tr>
</tbody>
</table>
If I understand correctly, you'll need something like this:
const copy=(id) => {
var value = document.getElementById("col"+id+"-input").value
var list = document.getElementsByClassName("col"+id+"-input")
for (i = 0; i < list.length; i++)
list[i].value = value
}
document.getElementById("col1-button").addEventListener("click", ()=>copy(1))
document.getElementById("col2-button").addEventListener("click", ()=>copy(2))
document.getElementById("col3-button").addEventListener("click", ()=>copy(3))
<table>
<tr>
<td><input id="col1-input" class="col1-input"><button id="col1-button">OK</button><br>
<td><input class="col1-input"></td>
<td><input class="col1-input"></td>
<td><input class="col1-input"></td>
<td><input class="col1-input"></td>
</tr>
<tr>
<td><input id="col2-input" class="col2-input"><button id="col2-button">OK</button><br>
<td><input class="col2-input"></td>
<td><input class="col2-input"></td>
<td><input class="col2-input"></td>
<td><input class="col2-input"></td>
</tr>
<tr>
<td><input id="col3-input" class="col3-input"><button id="col3-button">OK</button><br>
<td><input class="col3-input"></td>
<td><input class="col3-input"></td>
<td><input class="col3-input"></td>
<td><input class="col3-input"></td>
</tr>
</table>
Try this... JQuery solution.
Good luck!
$(function() {
$('button').on('click', function() {
var inputVal = $(this).prev().val();
// Plus one because arrays start at zero
var colIndex = $(this).parent().parent().children().index($(this).parent()) + 1;
$('table tr td:nth-child('+colIndex+')').not(':first')
.html(inputVal);
});
});
body { margin: 10px; }
table { max-width: 600px; }
td { min-width: 280px; }
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="">
<table class="table table-bordered">
<tr>
<td><input type="text"><button type="button">Copy</button></td>
<td><input type="text"><button type="button">Copy</button></td>
<td><input type="text"><button type="button">Copy</button></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</table>
</form>

How to get multiple selected cell array values with checkbox in jquery, then send with ajax post

How should I get an array value from a table cell when clicking checkbox with jQuery? If I've selected cell 1, I want to get array like ["BlackBerry Bold", "2/5", "UK"], but if I've selected all of them, I want to get all the data in the form of an array of arrays.
<table border="1">
<tr>
<th><input type="checkbox" /></th>
<th>Cell phone</th>
<th>Rating</th>
<th>Location</th>
</tr>
<tr>
<td align="center"><input type="checkbox"/></td>
<td>BlackBerry Bold 9650</td>
<td>2/5</td>
<td>UK</td>
</tr>
<tr>
<td align="center"><input type="checkbox" /></td>
<td>Samsung Galaxy</td>
<td>3.5/5</td>
<td>US</td>
</tr>
<tr>
<td align="center"><input type="checkbox"/></td>
<td>Droid X</td>
<td>4.5/5</td>
<td>REB</td>
</tr>
Please help.
Onclick get 3 children of the parent and add content to data. Used jquery nextAll for siblings and splice the 3 required.
Attached event to the table, onclick will check if element is INPUT.
If it's input, will get parent of that input which will be <td>.
For this parent element, will get three siblings using jquery.
Will add in selected if not present else delete, using indexOf.
CodePen for you to playaround: [ https://codepen.io/vivekamin/pen/oQMeXV ]
let selectedData = []
let para = document.getElementById("selectedData");
let tableElem = document.getElementById("table");
tableElem.addEventListener("click", function(e) {
if(e.target.tagName === 'INPUT' ){
let parent = e.target.parentNode;
let data = [];
$(parent).nextAll().map(function(index, node){
data.push(node.textContent);
})
let index = selectedData.indexOf(JSON.stringify(data))
if(index == -1){
selectedData.push(JSON.stringify(data));
}
else{
selectedData.splice(index,1);
}
para.textContent = "";
para.innerHTML = selectedData ;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table border="1" id="table">
<tr>
<th><input type="checkbox" /></th>
<th>Cell phone</th>
<th>Rating</th>
<th>Location</th>
</tr>
<tr>
<td align="center"><input type="checkbox"/></td>
<td>BlackBerry Bold 9650</td>
<td>2/5</td>
<td>UK</td>
</tr>
<tr>
<td align="center"><input type="checkbox" /></td>
<td>Samsung Galaxy</td>
<td>3.5/5</td>
<td>US</td>
</tr>
<tr>
<td align="center"><input type="checkbox"/></td>
<td>Droid X</td>
<td>4.5/5</td>
<td>REB</td>
</tr>
</table>
<h3> Selected Data: </h3>
<p id="selectedData"></p>
Updated to meet your needs.
create a function to build the array values based on looking for any checked inputs then going to their parents and grabbing the sibling text values
attach your change event to the checkbox click even.
I provided a fiddle below that will output the array in the console.
function buildTheArray(){
var thearray = [];
$("input:checked").parent().siblings().each(function(){
thearray.push($(this).text());
});
return thearray;
}
$("input[type='checkbox']").change(function(){
console.log(buildTheArray());
});
Fiddle:
http://jsfiddle.net/gcu4L5p6/

JQuery: Identify duplicate values in a table textbox column and highlight the textboxes

I'm using JQuery and I'm sure this is pretty simple stuff but I was unable to find a solution. I have an employee table with "Number" column which is editable(text box). I want to find the duplicates in the "Number" column and highlight those textboxes. For example in the table below I want to highlight all textboxes with values 10 and 20. Also when a edit is done and there are no longer duplicates, remove the highlight.
Here's the JSFiddle
Any Ideas?
<table id="employeeTable">
<tr>
<th>Id</th>
<th>Name</th>
<th>Number</th>
</tr>
<tr>
<td>1</td>
<td>John</td>
<td>10</td>
</tr>
<tr>
<td>2</td>
<td>Sally</td>
<td>20</td>
</tr>
<tr>
<td>3</td>
<td>Mary</td>
<td>10</td>
</tr>
<tr>
<td>4</td>
<td>Sam</td>
<td>30</td>
</tr>
<tr>
<td>5</td>
<td>Chris</td>
<td>20</td>
</tr>
</table>
There are different possibilities, basically you'll have to test if the value of an array exists more than one time, for example like this.
Update:
Using the value selector works fine in the initial state, but it seems that when a value is changed by direct user input or by calling .val(), the HTML attribute value is not changed (only the native JS .value). Therefore - to use the value selector in this context, the html value attribute is always updated with the JS .value.
function highlightDuplicates() {
// loop over all input fields in table
$('#employeeTable').find('input').each(function() {
// check if there is another one with the same value
if ($('#employeeTable').find('input[value="' + $(this).val() + '"]').size() > 1) {
// highlight this
$(this).addClass('duplicate');
} else {
// otherwise remove
$(this).removeClass('duplicate');
}
});
}
$().ready(function() {
// initial test
highlightDuplicates();
// fix for newer jQuery versions!
// since you can select by value, but not by current val
$('#employeeTable').find('input').bind('input',function() {
$(this).attr('value',this.value)
});
// bind test on any change event
$('#employeeTable').find('input').on('input',highlightDuplicates);
});
Updated fiddle is here.
I guess this is what you are exactly looking for:
Working : Demo
1) First for loop for taking all input values into an array inpValArr[]
2) Second for loop for sorting and finding out the duplicate ones.
3) Third for loop for adding class .highLight to duplicate ones.
Now all this is in a function: inputCheck() which is called on DOM Ready and after you edit the text field.
inputCheck();
$("#employeeTable input").bind("change paste keyup", function() {
inputCheck();
});
function inputCheck() {
var totalInp = $("#employeeTable input").length;
var inpValArr = [];
for (var j = 0; j < totalInp; j++) {
var inpVal = $("#employeeTable input:eq(" + j + ")").val();
inpValArr.push(inpVal);
}
var sorted_arr = inpValArr.sort();
var results = [];
for (var i = 0; i < inpValArr.length - 1; i++) {
if (sorted_arr[i + 1] == sorted_arr[i]) {
results.push(sorted_arr[i]);
}
}
$('#employeeTable input').removeClass('highLight');
for (var k = 0; k < totalInp; k++) {
$('#employeeTable :input[value="' + results[k] + '"]').addClass('highLight');
}
}
#employeeTable th,
#employeeTable td {
padding: 0.8em;
border: 1px solid;
}
#employeeTable th {
background-color: #6699FF;
font-weight: bold;
}
.highLight {
background: red;
}
<table id="employeeTable">
<tr>
<th>Id</th>
<th>Name</th>
<th>Number</th>
</tr>
<tr>
<td>1</td>
<td>John</td>
<td>
<input type="text" value="10" />
</td>
</tr>
<tr>
<td>2</td>
<td>Sally</td>
<td>
<input type="text" value="20" />
</td>
</tr>
<tr>
<td>3</td>
<td>Mary</td>
<td>
<input type="text" value="10" />
</td>
</tr>
<tr>
<td>4</td>
<td>Sam</td>
<td>
<input type="text" value="30" />
</td>
</tr>
<tr>
<td>5</td>
<td>Chris</td>
<td>
<input type="text" value="20" />
</td>
</tr>
</table>
You could easily give a class such as 'hasInput' to all td with inputs and then try a .each on all of them and check for value if they are 10 or 20 and then add a class to make them styled as you wish.
html:
<table id="employeeTable">
<tr>
<th>Id</th>
<th>Name</th>
<th>Number</th>
</tr>
<tr>
<td>1</td>
<td>John</td>
<td class="hasInput"><input type="text" value = "10"/></td>
</tr>
<tr>
<td>2</td>
<td>Sally</td>
<td class="hasInput"><input type="text" value = "20"/></td>
</tr>
<tr>
<td>3</td>
<td>Mary</td>
<td class="hasInput"><input type="text" value = "10"/></td>
</tr>
<tr>
<td>4</td>
<td>Sam</td>
<td class="hasInput"><input type="text" value = "30"/></td>
</tr>
<tr>
<td>5</td>
<td>Chris</td>
<td class="hasInput"><input type="text" value = "20"/></td>
</tr>
css:
#employeeTable th, #employeeTable td{
padding:0.8em;
border: 1px solid;
}
#employeeTable th{
background-color:#6699FF;
font-weight:bold;
}
.colored {
background-color: red;
}
js:
$('.hasInput > input').each(function() {
if ($(this).val() == 10 || $(this).val() == 20) {
$(this).addClass('colored');
}
});
DEMO
This would work:
var dupes=[], values=[];;
$('.yellow').removeClass('yellow');
$('#employeeTable td:nth-child(3) input').each(function(){
if($.inArray($(this).val(),values) == -1){
values.push($(this).val());
}
else{
dupes.push($(this).val());
}
});
$('#employeeTable td:nth-child(3) input').filter(function(){return $.inArray(this.value,dupes) == -1 ? false : true }).addClass('yellow');
#employeeTable th, #employeeTable td{
padding:0.8em;
border: 1px solid;
}
#employeeTable th{
background-color:#6699FF;
font-weight:bold;
}
.yellow{
background-color:yellow;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="employeeTable">
<tr>
<th>Id</th>
<th>Name</th>
<th>Number</th>
</tr>
<tr>
<td>1</td>
<td>John</td>
<td><input type="text" value = "10"/></td>
</tr>
<tr>
<td>2</td>
<td>Sally</td>
<td><input type="text" value = "20"/></td>
</tr>
<tr>
<td>3</td>
<td>Mary</td>
<td><input type="text" value = "10"/></td>
</tr>
<tr>
<td>4</td>
<td>Sam</td>
<td><input type="text" value = "30"/></td>
</tr>
<tr>
<td>5</td>
<td>Chris</td>
<td><input type="text" value = "20"/></td>
</tr>
</table>
Expanding on the answer provided by #axel.michel using .count() selector of Linq.js. I decided to go this route because I couldn't get the JQuery selector to work correctly provided in his answer. And I really like the Linq.js and find myself loving it more each time i implement a use of it.
var allTextBoxes = $().find('input:text');
// loop over all input fields on page
$(allTextBoxes)
.each(function() {
// select any other text boxes that have the same value as this one
if (Enumerable.from(allTextBoxes).count("$.value == '" + $(this).val() + "'") > 1) {
// If more than 1 have the same value than highlight this textbox and display an error message
$(this).addClass('duplicate');
$('#custom-field-validator').html('Custom fields must have unique names.');
valid = false;
} else {
// otherwise remove
$(this).removeClass('duplicate');
}
});
This is working fine without needing to worry about the value selector and syncing the value attributes.

Categories

Resources