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

I have created a table inside a form and one column consists of input elements. I have written a JavaScript function to validate each input. If invalid, the corresponding error message should be displayed beside respective input. In my case, for any input, the error message is always displayed beside the first input.
I tried using <div> and <span> tags with respective id values. For every invalid input the error message is displayed beside the first input and not the corresponding input.
Html table
<table>
<tr>
<td>S.No</td>
<td>Particulars</td>
<td>Amount</td>
<td></td>
</tr>
<tr>
<td>01</td>
<td>Annual Rent (Only of residential unit not owned by employer)</td>
<td><input type="number" name="ann_rent"><div id="ar_invalid"></div></td>
</tr>
<tr>
<td>02</td>
<td>Mediclaim (U/s. 80D of I.T. Act)</td>
<td><input type="number" name="medi"><div id="medi_invalid"></div></td>
</tr>
<tr>
<td>03</td>
<td>Interest paid for Home Loan</td>
<td><input type="number" name="home_int"><div id="home_invalid"></div></td>
</tr>
<tr>
<td>04</td>
<td>National Pension</td>
<td><input type="number" name="nat_pen"><div id="pen_invalid"></div></td>
</tr>
</table>
Javascript function
function validate() {
var a,b,c,d;
a = document.getElementsByName("ann_rent")[0].value;
b = document.getElementsByName("medi")[0].value;
c = document.getElementsByName("home_int")[0].value;
d = document.getElementsByName("nat_pen")[0].value;
if(!a || a < 0) {
document.getElementById("ar_invalid").innerHTML = text;
return false;
}
if(!b || b < 0) {
document.getElementById("medi_invalid").innerHTML = text;
return false;
}
if(!c || c < 0) {
document.getElementById("home_invalid").innerHTML = text;
return false;
}
if(!d || d < 0) {
document.getElementById("pen_invalid").innerHTML = text;
return false;
}
}
Table is inside this form
<form action="process_form.php" method="post" onSubmit="return validate();">
CSS
td, th {
text-align: left;
padding: 8px;
}
table {
margin-top: 30px;
margin-bottom: 10px;
font-family: arial, sans-serif;
width: 100%;
}
If user enters a negative value in input name="home_int", then the error message should be displayed beside input home_int. But actually, the error message is getting displayed beside input name="ann_rent". This situation is occurring for every input.

use th for headers. Add a new td for the error message
<table>
<tr>
<th>S.No</th>
<th>Particulars</th>
<th>Amount</th>
<th></th>
</tr>
<tr>
<td>01</td>
<td>Annual Rent (Only of residential unit not owned by employer)</td>
<td><input type="number" name="ann_rent"></td>
<td><div id="ar_invalid"></div></td>
</tr>
</table>
css
table td, table th {
padding: 20px;
border-spacing: 10px;
}
table {
border-collapse: collapse;
}

Assuming you have a button to submit for form validation which goes something like this:
<input type="submit" name="s" value="ds"/>
What happening is when your function gets inside the first if it then returns false and form will not be submitted so the other ifs wont perform any action in this situation so when you type any negative number in the first if, other ifs whether they are positive or negative wont work and the code will execute the message in the first div
but it will work and will show the message in the desired div if you will only put a negative number inside a specific textbox and all before will be positive

Change the "errors" divs to similar as below so you can have a simpler javascript code:
HTML:
<form action="/" method="post" onSubmit="return validate();">
<table>
<tr>
<td>S.No</td>
<td>Particulars</td>
<td>Amount</td>
<td></td>
</tr>
<tr>
<td>01</td>
<td>Annual Rent (Only of residential unit not owned by employer)</td>
<td><input type="number" name="ann_rent"><div id="ann_rent_invalid"></div></td>
</tr>
<tr>
<td>02</td>
<td>Mediclaim (U/s. 80D of I.T. Act)</td>
<td><input type="number" name="medi"><div id="medi_invalid"></div></td>
</tr>
<tr>
<td>03</td>
<td>Interest paid for Home Loan</td>
<td><input type="number" name="home_int"><div id="home_int_invalid"></div></td>
</tr>
<tr>
<td>04</td>
<td>National Pension</td>
<td><input type="number" name="nat_pen"><div id="nat_pen_invalid"></div></td>
</tr>
</table>
<input type="submit" value="Submit">
</form>
and in javascript:
function validate() {
var text = "error";
var required = ["ann_rent", "medi", "home_int", "nat_pen"];
var errors = 0;
required.forEach(function(element) {
var toselect = element + "_invalid";
var reqV = document.getElementsByName(element)[0].value;
if(!reqV || reqV < 0) {
document.getElementById(toselect).innerHTML = text;
errors++;
} else {
document.getElementById(toselect).innerHTML = null;
}
});
if(errors > 0){
return false;
}
}

Related

Multiple row form - how to update specific row when input field names are same in column

I have a report that, when it goes into input mode, creates a form where you have multiple rows of data, and on each row, there is a button and an input field. The input field name is the same for each row (it's easier for the CGI program to process the input that way). What I would also like, but having trouble doing, is if the user clicks on the button of that row, it should automatically update the input field in that same row. How can javascript find the input field for the same row where the button is?
I was stuck coming out of the gates, so don't even know where to start.
Here's a simplified version of the HTML:
<table>
<tr>
<td>Frank</td>
<td>Burns</td>
<td><input type="text" name="overtime" value="1000"></td>
<td><input type="button" name="averageIN" value="Average In" onclick="return avgIN('1000,'2000');">
</tr><tr>
<td>John</td>
<td>Doe</td>
<td><input type="text" name="overtime" value="500"></td>
<td><input type="button" name="averageIN" value="Average In" onclick="return avgIN('500,'2000');">
</tr>
</table>
Here's the incomplete javascript:
function avgIN(orig, avg) {
let text = "Request to Average In Overtime:\n\n"+
"Current OT Total: "+orig+"\n"+
"Averaged In Total: "+avg+"\n\n"+
"Click OK to accept";
if (confirm(text) == true) {
// do something here to set the overtime input field on the same row to the value of "avg"
}
else {
alert("Average In function canceled");
}
}
use event delegation...
and do something like that:
const myTable = document.querySelector('#my-table')
myTable.onclick = e =>
{
if (!e.target.matches('button[data-avg-in]')) return // exit
let
[orig, avg] = e.target.dataset.avgIn.split(',').map(Number)
, txt =
`Request to Average In Overtime:
Current OT Total: ${orig}
Averaged In Total: ${avg}
Click OK to accept`
;
if (confirm(txt))
{
e.target.closest('tr').querySelector('input[name="overtime[]"]').value = 'avg'
}
else
{
alert('Average In function canceled');
}
}
<table id="my-table">
<tr>
<td>Frank</td>
<td>Burns</td>
<td><input type="text" name="overtime[]" value="1000"></td>
<td><button data-avg-in="1000,2000" >Average In</button></td>
</tr>
<tr>
<td>John</td>
<td>Doe</td>
<td><input type="text" name="overtime[]" value="500"></td>
<td><button data-avg-in="500,2000" >Average In</button></td>
</tr>
</table>

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

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>

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

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

dynamically added dom-elements not responding to jQuery-function

Consider the following code:
$(document).ready(function(){
var table1 = $("table").eq(0);
var row_list;
var rows;
var x;
var y;
$("#mybutton").click(function(){
row_list = table1.find("tr");
rows = row_list.length;
x = $("#field_x").val();
y = $("#field_y").val();
if(x>rows || y>rows){
var num;
if(x>y) num=x;
else num=y;
var n = num-rows;
var row; table1.find("tr").eq(0).clone();
while(1){
row = table1.find("tr").eq(0).clone();
table1.append(row);
n--;
if(n===0) break;
}
n = num-rows;
var td;
while(1){
td = table1.find("td").eq(0).clone();
table1.find("tr").append(td);
n--;
if(n===0) break;
}
}
var text = $("#text").val();
var css = $("#css").val();
$("table:eq(0) tr:eq(" + (x-1) + ") td:eq(" + (y-1) + ")").text(text).css("color", css);
});
table1.find("td").click(function(){
$(this).html("");
});
});
* {
font: 14px normal Arial, sans-serif;
color: #000000;
}
table {
margin: 50px auto;
}
table, td {
border: 1px solid #aaa;
border-collapse: collapse;
}
th {
padding: 10px;
font-weight: bold;
}
td {
background-color: #eeeeee;
width: 80px;
height: 80px;
}
table:first-child tr td {
cursor: pointer;
}
td[colspan="4"]{
text-align:center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
<table>
<thead>
<tr>
<th colspan="4">Fill a field:</th>
</tr>
</thead>
<tbody>
<tr>
<td>Text: <br/><input type="text" id="text" value=""></td>
<td>Field X: <br/><input type="text" id="field_x" value=""></td>
<td>Field Y: <br/><input type="text" id="field_y" value=""></td>
<td>CSS: <br/><input type="text" id="css" value=""></td>
</tr>
<tr>
<td colspan="4"><button id="mybutton">Fill</button></td>
</tr>
</tbody>
</table>
What the program does is the following:
The user can choose a field by giving an x-value and a y-value. In this field the content from the input field with label "Text" is displayed.
- This part of the program works fine.
If the user chooses an x-value or a y-value larger than the current number of rows (columns), rows and columns are added until the number of rows/columns is equal to the value in the x-(or y-) field.
- This part of the program also works fine.
The only functionality that does not work is the following:
If the user clicks on one of the non-empty fields in the table, the content of the table is supposed to go back to its natural (empty) state.
To this end, the following function was added to the code (see last couple of lines in the javascript part of the code):
table1.find("td").click(function(){
$(this).html("");
});
This piece of code basically means:
If the user clicks on any box ("td") in the table, the content of this box should disappear.
This is more or less the most simple part of the code. But it's also the one aspect that doesn't work. More precisely: It works for the original boxes, but it doesn't work for any boxes that were added. - And I don't get why it behaved that way.
If you are dynamically adding elements to the DOM and expect to be attaching events to them, you should consider using event delegation via the on() function :
// This will wire up a click event for any current AND future 'td' elements
$(table1).on('click', 'td', function(){
$(this).html("");
});
Simply using click() on it's own will only wire up the necessary event handlers for elements that exist in the DOM at the time of that function being called.
You're assigning the event handlers before the user has a chance to input any data. This means that if an additional row or column is added, the new <td>s need event handlers added manually.
Alternately, you can add a single click handler to the entire table:
table1.click(function (ev) { $(ev.target).html(''); }
The ev.currentTarget property will be the <table> element because that's the element the event handler is registered to, but the ev.target property will be the <td> element that you're looking for.
Here's a JSFiddle to experiment with.
Hey there here's what I thought the answer might be,
HTML File:
<!DOCTYPE html>
<html lang="de-DE">
<head>
<meta charset="UTF-8" />
<style>
* {
font: 14px normal Arial, sans-serif;
color: #000000;
}
table {
margin: 50px auto;
}
table, td {
border: 1px solid #aaa;
border-collapse: collapse;
}
th {
padding: 10px;
font-weight: bold;
}
td {
background-color: #eeeeee;
width: 80px;
height: 80px;
}
table:first-child tr td {
cursor: pointer;
}
td[colspan="4"]{
text-align:center;
}
.pre-height {
min-height: 80px;
}
</style>
</head>
<body>
<table>
<tbody>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td class="pre-height"></td>
<td class="pre-height"></td>
<td class="pre-height"></td>
<td class="pre-height"></td>
</tr>
</tbody>
</table>
<table>
<thead>
<tr>
<th colspan="4">Fill a field:</th>
</tr>
</thead>
<tbody>
<tr>
<td>Text: <br/><input type="text" id="text" value=""></td>
<td>Field X: <br/><input type="text" id="field_x" value=""></td>
<td>Field Y: <br/><input type="text" id="field_y" value=""></td>
<td>CSS: <br/><input type="text" id="css" value=""></td>
</tr>
<tr>
<td colspan="4"><button id="myButton">Fill</button></td>
</tr>
</tbody>
</table>
<script src="jquery.min.js"></script>
<script src="jack.js"></script>
</body>
</html>
JACK.JS file:
window.onload = function() {
'use strict';
/**
* Appends 'n' number of rows to the table body.
*
* #param {Number} n - Number of rows to make.
*/
var makeRows = function(n) {
let tbody= document.getElementsByTagName("table")[0].getElementsByTagName("tbody")[0],
tr = document.querySelector("table:first-of-type tbody tr");
for (let i = 0; i < n; i++) {
let row = Node.prototype.cloneNode.call(tr, true);
tbody.appendChild(row);
}
};
/**
* Appends 'n' number of cells to each row.
*
* #param {Number} n - Number of cells to add to each row.
*/
var makeColumns = function(n) {
let addNCells = (function(n, row) {
for (let i = 0; i < n; i++) {
let cell = Node.prototype.cloneNode.call(td, true);
row.appendChild(cell);
}
}).bind(null, n);
let tbody= document.getElementsByTagName("table")[0].getElementsByTagName("tbody")[0],
td = document.querySelector("table:first-of-type tbody tr td"),
rows = document.querySelectorAll("table:first-of-type tbody tr");
rows.forEach(function(row) {
addNCells(row);
});
};
document.getElementById("myButton").addEventListener("click", () => {
let x = document.getElementById("field_x").value,
y = document.getElementById("field_y").value;
makeColumns(x);
makeRows(y);
});
/**
* Newly added code
*/
(function() {
let table = document.querySelector("table");
// We will add event listener to table.
table.addEventListener("click", (e) => {
e.target.innerHTML = "";
e.target.style.backgroundColor = "orange";
});
})();
};
Edit: And I didn't even answer the question completely. You might wanna attach event listener to the nearest non-dynamic parent so that click event will bubble up and you can capture that, check the code under the comment newly added code.

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