Dynamically change table cell with user input in Javascript - 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.

Related

How do I assign an ID to a row that gets called on buttonclick in javascript

I'm trying to assign an unique id to each row to then modify rows with specific number id's. However since the function is called every time on button click, I always get the same output for the number.
Here is my JavaScript Function
[<script type="text/javascript">
function insert_row(){
var firstName = document.getElementById('first_name').value;
var lastName = document.getElementById('last_name').value;
var human = "human";
var id =1;
var table = document.getElementById("saving_table");
// Create an empty <tr> element and add it to the 1st position of the table:
var row = table.insertRow(1);
row.id=id;
var rowId = row.id;
// Insert new cells (<td> elements) at the 1st and 2nd position of the "new" <tr> element:
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
// Add some text to the new cells:
cell1.innerHTML = firstName;
cell2.innerHTML = lastName;
cell3.innerHTML = human+ rowId.toString();
id++;
}
</script>][1]
Here is my table declaration
<div class="container">
<table class="table table-bordered" id="saving_table">
<caption>Classmates</caption>
<thead>
<tr>
<th>FirstName</th>
<th>LastName</th>
<th>Human or Vampire?</th>
</tr>
</thead>
</table>
<button class="btn btn-primary" onclick="insert_row()">Submit</button>
and an image of my output just incase:
Basically you just need to move the id variable outside of the function. That way it's only set to 1 when your code loads, and then each function call increments it.
// global
var id = 1;
function insert_row() {
// ...
demo
// global
var id = 1;
function insert_row() {
var firstName = document.getElementById('first_name').value;
var lastName = document.getElementById('last_name').value;
var human = "human";
var table = document.getElementById("saving_table");
// Create an empty <tr> element and add it to the 1st position of the table:
var row = table.insertRow(1);
row.id = id;
var rowId = row.id;
// Insert new cells (<td> elements) at the 1st and 2nd position of the "new" <tr> element:
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
// Add some text to the new cells:
cell1.innerHTML = firstName;
cell2.innerHTML = lastName;
cell3.innerHTML = human + rowId.toString();
id++;
}
<div class="container">
<table class="table table-bordered" id="saving_table">
<caption>Classmates</caption>
<thead>
<tr>
<th>FirstName</th>
<th>LastName</th>
<th>Human or Vampire?</th>
</tr>
</thead>
</table>
<input id="first_name" />
<input id="last_name" />
<button class="btn btn-primary" onclick="insert_row()">Submit</button>
</div>
Since the id variable is being initialized in each function call, all the rows end up having the same id(that is, 1). One of the ways of solving this would be to simply place the var id = 1; declaration before the start of function insert_row() as a global variable.
However, in order to avoid using global variables, we could get the count of all the existing rows of the table and add 1 to it to get the new id in the following manner:
[<script type="text/javascript">
function insert_row(){
var firstName = document.getElementById('first_name').value;
var lastName = document.getElementById('last_name').value;
var human = "human";
var table = document.getElementById("saving_table");
// get count of the number of rows that already exist
var rowCount = table.getElementsByTagName("tr").length;
var id = rowCount + 1;
// Create an empty <tr> element and add it to the 1st position of the table:
var row = table.insertRow(id);
row.id=id;
var rowId = row.id;
// Insert new cells (<td> elements) at the 1st and 2nd position of the "new" <tr> element:
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
// Add some text to the new cells:
cell1.innerHTML = firstName;
cell2.innerHTML = lastName;
cell3.innerHTML = human+ rowId.toString();
id++;
}
][1]
The HTML code would remain the same. In case your application is large or is headed towards being a large project, I'd strongly recommend using the second method instead of defining a global variable. Global variables tend to get very difficult to manage as the application size grows.
Please, make better code:
1) increase insertRow for each new line
2) don't repeat all document.getElementById for each call
3) don't mix html code with JS ( onclick="insert_row()" )
4) If you made a TABLE with THEAD, use TBODY
const
in_firstName = document.getElementById('first_name'),
in_lastName = document.getElementById('last_name'),
human_str = "human",
tableBody = document.querySelector('#saving_table tbody')
;
var Table_Row_ID = 0;
document.getElementById('insert-row').onclick = function()
{
// Create an empty <tr> element and add it to the 1st position of the table:
let row = tableBody.insertRow(Table_Row_ID);
row.id = ++Table_Row_ID;
// Insert new cells (<td> elements) at the 1st and 2nd position of the "new" <tr> element:
let
cell1 = row.insertCell(0),
cell2 = row.insertCell(1),
cell3 = row.insertCell(2)
;
// Add some text to the new cells:
cell1.textContent = in_firstName.value;
cell2.textContent = in_lastName.value;
cell3.textContent = human_str + row.id;
}
<div class="container">
<table class="table table-bordered" id="saving_table">
<caption>Classmates</caption>
<thead>
<tr>
<th>FirstName</th>
<th>LastName</th>
<th>Human or Vampire?</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<div class="container">
<input type="text" id="first_name" placeholder="first_name" />
<input type="text" id="last_name" placeholder="last_name" />
<button class="btn btn-primary" id="insert-row">Add Row</button>
</div>
Declare the counter outside of function.
Demo
Details commented in demo
// Reference tags
var btn = document.querySelector('button');
var first = document.getElementById('firstName');
var last = document.getElementById('lastName');
var spec = document.getElementById('species');
// Declare counter
var i = 0;
function insert_row(e) {
// Reference <tbody> (Not <table>)
var table = document.querySelector("tbody");
// Insert <tr> (No index is needed)
var row = table.insertRow();
// Add ID to <tr>
row.id = 'r' + i;
// for every loop...
for (let c = 0; c < 3; c++) {
// ...insert a <td>...
var cell = row.insertCell(c);
// ...1st loop add the value of first name input as text...
if (c === 0) {
cell.textContent = first.value;
// ...2nd loop add the value of last name input as text...
} else if (c === 1) {
cell.textContent = last.value;
// ...3rd loop add the value of species select as text...
} else if (c === 2) {
cell.textContent = spec.value;
// ...otherwise just end loop
} else {
break;
}
}
// Increment counter
i++;
}
// Add click event handler to button
btn.onclick = insert_row;
table {
table-layout: fixed;
width: 75%;
margin: 10px auto;
}
th {
width: 33%
}
td {
text-align: center
}
caption {
font-size: 1.2rem;
font-weight: 900;
}
input,
select,
button {
display: inline-block;
font: inherit;
height: 3ex;
line-height: 3ex;
vertical-align: middle;
}
select,
button {
height: 4ex;
}
button {
float: right
}
<div class="container">
<table class="table table-bordered" id="saving_table">
<caption>Classmates</caption>
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Species</th>
</tr>
</thead>
<tbody></tbody>
</table>
<input id='firstName' placeholder='First'>
<input id='lastName' placeholder='Last'>
<select id='species'>
<option value=''>Species</option>
<option value='Human 🕵'>Human 🕵</option>
<option value='Vampire 🧛'>Vampire 🧛</option>
</select>
<button class="btn btn-primary">Submit</button>
</div>

Find values in table cells with 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.

searching text within Html table

I just googling to find a script that I can use to find a text within HTML table.
Like I create a table of student names which have many columns and rows. I have a good script too that display whatever I try to search but it display full row...
function searchSname() {
var input, filter, found, table, tr, td, i, j;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
table = document.getElementById("myTable");
tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td");
for (j = 0; j < td.length; j++) {
if (td[j].innerHTML.toUpperCase().indexOf(filter) > -1) {
found = true;
}
}
if (found) {
tr[i].style.display = "";
found = false;
} else {
tr[i].style.display = "none";
}
}
}
<input id='myInput' onkeyup='searchSname()' type='text'>
<table id='myTable'>
<tr>
<td>AB</td>
<td>BC</td>
</tr>
<tr>
<td>CD</td>
<td>DE</td>
</tr>
<tr>
<td>EF</td>
<td>GH</td>
</tr>
</table>
But know I am looking for making some changes to display exact text whatever I searched instead of full row like it will display text that I type to search and hide other unmatched fully....
Kindly let me know is it possible to display text only that I type to search within a table? Like if I try to find student name "AB" then it should display AB only instead of "AB BC".
This is much simpler than you are making it.
var cells = document.querySelectorAll("#myTable td");
var search = document.getElementById("myInput");
search.addEventListener("keyup", function(){
for(var i = 0; i < cells.length; ++i){
// This line checks for an exact match in a cell against what the
// user entered in the search box
//if(cells[i].textContent.toLowerCase() === search.value.toLowerCase()){
// This checks for cells that start with what the user has entered
if(cells[i].textContent.toLowerCase().indexOf(search.value.toLowerCase()) === 0){
cells.forEach(function(element){
element.style.display = "none";
});
cells[i].style.background = "yellow";
cells[i].style.display = "table-cell";
break;
} else {
cells[i].style.background = "white";
cells.forEach(function(element){
if(cells[i] !== element){
element.style.display = "table-cell";
}
});
}
}
});
table, td { border:1px solid black; border-collapse: collapse;}
<input id='myInput'>
<table id='myTable'>
<tr>
<td>AB</td>
<td>BC</td>
</tr>
<tr>
<td>CD</td>
<td>DE</td>
</tr>
<tr>
<td>EF</td>
<td>GH</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";

Add table values to input field on button click

I have a DataTable that stores names only. I want to have a button that will add all the names in the DataTable to an text input field.
<div id="myTabDiv">
<table name="mytab" id="mytab1">
<thead>
<tr>
<th>name</th>
</tr>
</thead>
<tbody>
<tr>
<td>chris</td>
</tr>
<tr>
<td>mike</td>
</tr>
</tbody>
</table>
<button id="add" >ADD</button>
<input type="text" id="text">
</div>
After click the "add" button, I want the names to appear in the text field separated by a comma.
And if possible, If the button is clicked again, remove the names?
I created the whole solution on codepen. This is the function used:
var clicks = 0;
function csv() {
var box = document.getElementsByName('text')[0];
if(clicks === 0){
var newcsv = "";
var tds = document.getElementsByTagName("TD");
for(var i = 0; i < tds.length; i++)
{
newcsv += tds[i].innerHTML;
if(i != tds.length-1) newcsv += ",";
}
box.value = newcsv;
clicks++;
}
else{
clicks = 0;
box.value = "";
}
}
This is bound to onclick event of a button.
Assign id to input
<input type=text id="textbox"/>
Just loop though table
var table = document.getElementById("mytab1");
var textbox=document.getElementById("textbox")
for (var i = 0, row; row = table.rows[i]; i++) {
for (var j = 0, col; col = row.cells[j]; j++) {
if(textbox.value=="")
{
textbox.value=row.cells[j].innerText;
}
else
{
textbox.value+= textbox.value+','+row.cells[j].innerText;
}
}
}

Categories