Find values in table cells with Javascript - javascript

I'm using a dynamic table in HTML, but I need to verify the values are not repeated. I'm trying to do it with the value inside the cell rather than the text. These are the values and what I have so far:
var tBody = $("#tablaAplicaciones > TBODY")[0];
//Add Row.
var row = tBody.insertRow(-1);
//Add Name cell.
var cell = $(row.insertCell(-1));
cell.html(nameCountry);
cell.val(idCountry);
//Add Country cell.
cell = $(row.insertCell(-1));
cell.html(nameCompany);
cell.val(idCompany);
if (($('#tablaApp tr > td:contains(' + countryName + ') + td:contains(' + companyName + ')').length) == 1) {
.
.
.
}

Welcome to Stack Overflow. Consider the following code.
$(function() {
var idCountry = "9";
var nameCountry = "United States";
var idCompany = "9";
var nameCompany = "Genentech";
var tBody = $("#tablaAplicaciones > tbody");
//Create Row
var row = $("<tr>");
//Add Country cell to Row
$("<td>", {
class: "name-country"
})
.data("id", idCountry)
.html(nameCompany)
.appendTo(row);
//Add Company cell to Row
$("<td>", {
class: "name-company"
})
.data("id", idCompany)
.html(nameCompany)
.appendTo(row);
// Assume vales are not in the table
var found = -1;
$("tr", tBody).each(function(i, el) {
// Test each row, if value is found set test to tue
if ($(".name-country", el).text().trim() == nameCountry) {
found = i;
}
if ($(".name-company", el).text().trim() == nameCompany) {
found = i;
}
});
if (found == -1) {
// If test is false, append the row to table
row.appendTo(tBody);
console.log("Row Added", row);
} else {
console.log("Values already in Table, row: " + found);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="tablaAplicaciones">
<thead>
<tr>
<th>Country</th>
<th>Company</th>
</tr>
</thead>
<tbody>
<tr>
<td data-id="1" class="name-country">United States</td>
<td data-id="1" class="name-company">Apple Inc.</td>
</tbody>
</table>
Using .each(), you can iterate over each row and compare the values. A variable can be used as a flag to indicate if the needle was found in the haystack. If not found, you can append the row. Otherwise, do not add the row.
Hope that helps.

Related

Jquery how to judge the td I clicked is the first row or last row,and row index and column index?

I have a table like this link.
How can I know the td(input) I clicked is the first row or last row?
And how can I know the column index of td and the row index of td I clicked?
I know I can use $(this), but how to do?
$("#table_reach_condition_appoint tbody td").click(function(){
//$(this)
})
Here is an example how you can do it. index() returns the index of the current position of the selected element. It starts with index 0. Therefore we need to add +1 to the result to get the correct row/column number.
$(function(){
$('td').on('click', function(){
var columnNumber = $(this).index() + 1; // add 1 because index starts with 0
var rowNumber = $(this).parent('tr').index() + 1;
//Check if the culculated row number is 1
firstcolumn = (columnNumber === 1);
firstRow = (rowNumber === 1);
//Compare the clicked element with the last element using jQuery's is() function.
lastRow = $(this).parent('tr').is(':last-child');
lastColumn = $(this).is(':last-child');
console.log('clicked on: ' + $(this).text());
console.log('row: ' + rowNumber);
console.log('column: ' + columnNumber);
if(firstcolumn) {
console.log('firstColumn');
}
if(firstRow) {
console.log('firstRow');
}
if(lastRow) {
console.log('lastRow');
}
if(lastColumn) {
console.log('lastColumn');
}
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>1A</td>
<td>2A</td>
<td>3A</td>
<td>4A</td>
</tr>
<tr>
<td>1B</td>
<td>2B</td>
<td>3B</td>
<td>4B</td>
</tr>
</table>
$("#table_reach_condition_appoint tbody td").each(function() {
$(this).on('click', function() {
var row = $(this).parent('tr').index(),
column = $(this).index();
console.log(row, column);
});
})
Row and Column will start at 0 unless otherwise specified.
$("#table_reach_condition_appoint tbody td").click(function(){
var tbl_row_count = $('#table_reach_condition_appoint>tbody>tr').length;
var col_no = parseInt($(this).index())+1;
var row_no = parseInt($(this).closest('tr').index())+1;
if(row_no == 1)
{
alert('first row');
}
if(row_no == tbl_row_count)
{
alert('last row');
}
alert('You clicked row no'+row_no+' col no'+col_no);
});

Adding table rows and cells

I tried to make the page add rows and five cells to each table, however I'm having some problems. I appended the row first to the table then followed by looping through the and adding five cells to each row, however whenever I ran it in my web browser it produced this:
I want the cells to be a child of the table row.
function addRows(ramnt) {
if(ramnt > 0){
var cellcount = 5;
var tccount = 0;
table.append('<tr>');
console.log('Appended <tr>');
while(tccount < cellcount){
tccount = tccount + 1;
table.append('<td id="Cell-' + tccount + '" class="gencell"></td>');
}
if (tccount = cellcount){
table.append('</tr>');
ramnt = ramnt - 1;
addRows(ramnt);
}
}
}
console.log('Working');
var table = $('Table');
addRows(5);
I would advise making your function a little more dynamic. Here is what I would suggest:
function addRows(rc, to) {
if(rc > 0){
var cellcount = 5;
for(var i = 0; i < rc; i++){
var row = $("<tr>", { id: "Row-" + i });
for(var c = 0; c < cellcount; c++){
row.append("<td id='Cell-" + c + "' class='gencell'></td>");
}
to.append(row);
console.log("Row " + i + " created");
}
return true;
} else {
return false;
}
}
Then you can pass the Number of Rows and the Table Object like so:
addRows(5, $("table"));
As I said, I would advise setting your table like so:
<table id="myTable"></table>
This way if you later add another table or do something differnt, you can still use the same code:
addRows(5, $("#myTable"));
Working Example: https://jsfiddle.net/Twisty/Lysr2n5v/
You can take a bit further to write to function to accept X number of Rows, N number of Cells per Row, and the table Object: https://jsfiddle.net/Twisty/Lysr2n5v/2/
function addRows(rc, cc, to) {
if(rc > 0){
for(var i = 0; i < rc; i++){
var row = $("<tr>", { id: "Row-" + i });
for(var c = 0; c < cc; c++){
row.append("<td id='Cell-" + c + "' class='gencell'></td>");
}
to.append(row);
console.log("Row " + i + " created");
}
return true;
} else {
return false;
}
}
When you call table.append('<tr>'), jQuery inserts both opening and closing tags. I tried this:
Then you call table.append('<td id="Cell-' + tccount + '" class="gencell"></td>');, which appends the td element at the end of the table, so it goes after the tr you appended before.
What you need to do is insert the tr as you did, but then select this tr and append into it. So something like this:
table.find('tr:last').append('<td id="Cell-' + tccount + '" class="gencell"></td>');
You need to create a row, append all the columns to that row, then append the row to the table like below.
I would also recommend adding logic to check the number of columns already present in the table and make sure you dont add more than are there now as that would not be valid.
With the below:
addRows(5,5) - will add 5 rows to every table on the page where each row will the same number of columns as the table currently has or 5 columns if the table doesnt currently have any columns
addRows(5,5,'#myTable') - will add 5 rows to the table with the id myTable where each row will the same number of columns as the table currently has or 5 columns if the table doesnt currently have any columns
function addRows(rowCount, colCount, table) {
var $tables= table ? $(table) : $('table');
$tables.each(function(){
console.log('table');
$this=$(this);
colCount =$this.find('tr:eq(0)').find('td').length || colCount // limit the number of added cols to the numer already present
for(r=0;r<rowCount;r++){
var $row=$('<tr>');
for(c=0;c<colCount;c++){
$row.append('<td>');
}
$this.append($row);
}
});
}
addRows(5,5);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="1"></table>
<br>
<br>
<br>
<br>
<br>
<table border="1"><tr>
<td>some content</td>
<td>some content</td>
<td>some content</td>
</tr></table>

Add rows and data

So currently I can add rows with this code:
function addRow(){
var tableRef = document.getElementById('myTable').getElementsByTagName('tbody')[0];
// Insert a row in the table at row index 0
var newRow = tableRef.insertRow(tableRef.rows.length);
// Insert a cell in the row at index 0
var newCell = newRow.insertCell(0);
// Append a text node to the cell
var newText = document.createTextNode('New row')
newCell.appendChild(newText);
}
Here is my table:
<table id="myTable" border="2px">
<tbody>
<td>
Module 1
</td>
<td>
Introduction
</td>
<td id="info">
</td></tr>
<tr>
<td>
<div id="button"> Add Another Row </div>
</td></tr>
</tbody>
</table>
Here is how I add data to the row:
function showChoices()
{
//retrieve data
var selLanguage = document.getElementById("productchoice3");
//set up output string
var result="<ul> \n";
//step through options
for (i = 0; i < selLanguage.length; i++)
{
//examine current option
currentOption = selLanguage[i];
//print it if it has been selected
if (currentOption.selected == true)
{
console.log(currentOption.label);
result += " <li>" + currentOption.label + "<br>" + currentOption.value + "<\/li> \n";
} // end if
} // end for loop
//finish off the list and print it out
result += "<\/ul> \n";
output = document.getElementById("info");
output.innerHTML = result;
document.getElementById('info').style.display='block';
}
What I want to do is have the "add another row" move down each time I click it, so I can add infinite rows, and have a way to add data to the newest row that was created.
You could easily add an id to the row, by doing:
var newRow = tableRef.insertRow(tableRef.rows.length);
newRow.id = "whateverYouWant";

Dynamically change table cell with user input in Javascript

This is what I'm trying to do: I have a table, created from Javascript with user input in each cell. This table is just to confirm that the data entered by the user is correct. If the user sees an error, they click on the cell which needs editing, and it puts a textbox in the table cell with the current cell data. The user will then be able to submit changes or discard the changes if they clicked on the wrong cell. This is currently what I have:
<table id = "confirm">
<tr><th>Firstname</th><td id = "txtFirstname" onclick = "update(this.id)">Adan</td></tr>
<tr><th>Lastname</th><td>Smith</td></tr>
<tr><th>Username</th><td>ASmith</td></tr>
<tr><th>Email</th><td>abc#123.com</td></tr>
<tr><th>Phone</th><td>123-456-7890</td></tr>
</table>
<script type = "text/javascript">
function update(id){
//Get contents off cell clicked
var content = document.getElementById(id).firstChild.nodeValue;
//Switch to text input field
document.getElementById(id).innerHTML = "<input type = 'text' name = 'txtNewInput' id = 'txtNewInput' value = '" + content + "'/>";
}
</script>
This is what my current code does: When user clicks on the cell, it replaces it with the current text inside a textbox, which is great, but when you try to edit the text, it calls the function over again replacing the text with "null". Please help me figure this out!
It is caused by event bubbling. You didn't want onclick to apply to input, but unfortunately this is not the case. To solve this problem, simply do this (taken from http://jsfiddle.net/DerekL/McJ4s/)
table td, th{
border: 1px solid black;
}
<table id="confirm">
<tr>
<th>Firstname</th>
<td contentEditable>Adan</td>
</tr>
<tr>
<th>Lastname</th>
<td>Smith</td>
</tr>
<tr>
<th>Username</th>
<td>ASmith</td>
</tr>
<tr>
<th>Email</th>
<td>abc#123.com</td>
</tr>
<tr>
<th>Phone</th>
<td>123-456-7890</td>
</tr>
</table>
Why do it with JavaScript when simple HTML can do the same thing? ;)
Internet Explorer:
There is a strange "bug" in IE that it won't allow a table cell to be editable (why, Microsoft?) So you have to wrap your content with a <div> (taken from http://jsfiddle.net/DerekL/McJ4s/3/):
table td,
th {
border: 1px solid black;
}
<table id="confirm">
<tr>
<th>Firstname</th>
<td>
<div contenteditable>Adan</div>
</td>
</tr>
<tr>
<th>Lastname</th>
<td>Smith</td>
</tr>
<tr>
<th>Username</th>
<td>ASmith</td>
</tr>
<tr>
<th>Email</th>
<td>abc#123.com</td>
</tr>
<tr>
<th>Phone</th>
<td>123-456-7890</td>
</tr>
</table>
<table id = "confirm">
<tr><th>Firstname</th><td id = "txtFirstname" onclick = "update(this.id)">Adan</td></tr>
<tr><th>Lastname</th><td>Smith</td></tr>
<tr><th>Username</th><td>ASmith</td></tr>
<tr><th>Email</th><td>abc#123.com</td></tr>
<tr><th>Phone</th><td>123-456-7890</td></tr>
</table>
<script type = "text/javascript">
function update(id){
//Get contents off cell clicked
var content = document.getElementById(id).firstChild.nodeValue;
//Switch to text input field
document.getElementById(id).innerHTML = "<input type = 'text' name = 'txtNewInput' id = 'txtNewInput' value = '" + content + "'/>";
}
</script>
Added an if statement in the update() function. Changed it to:
<script type = "text/javascript">
function update(id){
if(document.getElementById(id).firstChild != "[object HTMLInputElement]"){
//Get contents off cell clicked
var content = document.getElementById(id).firstChild.nodeValue;
//Switch to text input field
document.getElementById(id).innerHTML = "<input type = 'text' name = 'txtNewInput' id = 'txtNewInput' value = '" + content + "'/>";
}
}
</script>
That works like a charm!
var table = document.getElementById('');
var rowCount = table.rows.length;
var noRowSelected = 1;
for(var i=1; i<rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if(null != chkbox && true == chkbox.checked) {
if(rowCount <= 1) {
break;
}
document.getElementById("").value = row.cells[1].innerHTML;
document.getElementById("").value = row.cells[2].innerHTML;
document.getElementById("").value = row.cells[3].innerHTML;
document.getElementById("").value = row.cells[4].innerHTML;
}
}
The Above Example the checkbox must be need for the each row.then we used this check box to get the current edit row values in the dynamic table. then to use the id for edit field to set valued got from the table.
Dynamically Change the Table Row Value:
var table = document.getElementById('');
var rowCount = table.rows.length;
var noRowSelected = 1;
for(var i=1; i<rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if(null != chkbox && true == chkbox.checked) {
if(rowCount <= 1) {
break;
}
document.getElementById("").value = row.cells[1].innerHTML;
document.getElementById("").value = row.cells[2].innerHTML;
document.getElementById("").value = row.cells[3].innerHTML;
document.getElementById("").value = row.cells[4].innerHTML;
}
}
The Above Example the checkbox must be need for the each row.then we used this check box to get the current edit row values in the dynamic table.

Finding a colSpan Header for one of the cells or td's is Spans

I have multiple column headers that spans of multiple column and I would like to find the correct header number/count for the columns.
I want to enter a column number and get the header: example column 5 is RDataTest6 $('td.eq(5)) and its header is HTest3 $('th.eq(2))
Example:
<table>
<tr>
<th>HTest1</th>
<th colSpan="2">HTest2</th>
<th colSpan="4">HTest3</th>
<th colSpan="2">HTest4</th>
</tr>
<tr>
<td>RDataTest1</td>
<td>RDataTest2</td>
<td>RDataTest3</td>
<td>RDataTest4</td>
<td>RDataTest5</td>
<td>RDataTest6</td>
<td>RDataTest7</td>
<td>RDataTest8</td>
<td>RDataTest9</td>
</tr>
</table>
​
Edit: You should implement a simple array that hold the header location, see below,
var thLocator = [], colCount = 1;
$table.find('tr:first th').each(function () {
for (var i = 0; i < this.colSpan; i++) {
thLocator.push(colCount);
}
colCount++;
});
$table.find('td').click(function () {
alert(thLocator[$(this).index()]);
});
And then anytime You can get the location of a td column. See DEMO -> Click on any TD to identify its col head position.
I am not sure which count you want so I wrote down all col count. See DEMO
$(function() {
var $table = $('table');
alert('Table Header Count ' + $table.find('tr:first th').length);
var thCount = 0;
$table.find('tr:first th').each(function () {
thCount += this.colSpan;
});
alert('Computed TH Count ' + thCount );
alert('Table TD Col Count ' + $table.find('tr:eq(1) td').length);
});
That's easy, as long as you don't have any rowspans:
function getCell(tr, col) {
var cell = tr.firstElementChild;
while (cell && (col -= cell.colSpan || 1)>=0)
cell = cell.nextElementSibling;
return cell;
}
See demonstration.

Categories