Show all names found in table when click display button - javascript

I need to show all names found in table #tb and display as list using jQuery when the user clicks the display button.
My code is below. I can add successfully, but how can I take data from column name and show as list?
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script>
$(function () {
$("#btn").click(function() {
var x = $("#txt1").val();
var y = $("#txt2").val();
var z = $("#mycountry").val();
$("#tb").append("<tr> <td>" + x + "</td> <td>" + y + "</td> <td>" + z + "</td><td> <input type='button'class='c' value='Delete'/></td><td> <input type='button' class='d' value='Edit'/></td></tr>");
});
$("#tb").on("click", ".c", function () {
//$(this).parent().parent().remove();
$(this).closest('tr').remove();
});
$("#tb").on("click", ".d", function () {
var row = $(this).closest('tr').toggleClass("editing");
row.find("td").slice(0, 3).prop("contenteditable", row.hasClass("editing"));
});
});
</script>
<style>
.editing {
background: yellow;
}
</style>
</head>
<body>
<div>
ID
<input type="text" id="txt1" /><br />
Name
<input type="text" id="txt2" /><br />
Country:
<select id="mycountry">
<option>---select---</option>
<option>Egypt</option>
<option>qatar</option>
<option>saudia</option>
<option>emarates</option>
</select><br />
<input type="button" value="add" id="btn" />
<input type="button" value="display" id="btndis" />
<table>
<thead>
<tr>
<td>
ID
</td>
<td>
Name
</td>
<td>
Country
</td>
<td>
</tr>
</thead>
<tbody id="tb"></tbody>
</table>
</div>
</body>
</html>

Try this:
https://jsfiddle.net/ionutmihai1995/euk6xkzp/
$('#btndis').click(function(){
$('ul').empty();
$("#tb").find('tr').each(function(i,el){
var $tds = $(this).find('td');
//for name
$('ul').append("<li>"+$tds.eq(1).text()+"</li>");
});
});

Please check below code.
$("#btndis").on('click',function(){
$("body").append("<ul id='listNames''></ul>");
$('#tb td:nth-child(2)').each(function() {
$("#listNames").append("<li>"+$(this).text()+"</li>")
});
})
Please refer code on this Link. https://jsfiddle.net/gq5f5ux2/2/
On click of the display button iterate loop through all the tr>td-second child to get all the names and then append a UL and LI in the body to display list all the names.

Add a class for colum called "name" and then you can iterate over and select the text in the element
<td class="name">John</td>
Then in JQuery:
$(document).ready(function() {
$('#tb').find('tr').each(function() {
var name = $(this).find('.name').text();
$('#result').append('<p>'+name+'</p>');
});
});
Working example

check this JsFiddle Demo
HTML
<div>
ID
<input type="text" id="txt1" />
<br /> Name
<input type="text" id="txt2" />
<br /> Country:
<select id="mycountry">
<option>---select---</option>
<option>Egypt</option>
<option>qatar</option>
<option>saudia</option>
<option>emarates</option>
</select>
<br />
<input type="button" value="add" id="btn" />
<input type="button" value="display" id="btndis" />
<table>
<thead>
<tr>
<td>
ID
</td>
<td>
Name
</td>
<td>
Country
</td>
<td>
</tr>
</thead>
<tbody id="tb"></tbody>
</table>
<ul id="ulNames">
</ul>
</div>
JS
$(function() {
$("#btn").click(function() {
var x = $("#txt1").val();
var y = $("#txt2").val();
var z = $("#mycountry").val();
$("#tb").append("<tr> <td>" + x + "</td> <td>" + y + "</td> <td>" + z + "</td><td> <input type='button'class='c' value='Delete'/></td><td> <input type='button' class='d' value='Edit'/></td></tr>");
});
$("#tb").on("click", ".c", function() {
//$(this).parent().parent().remove();
$(this).closest('tr').remove();
});
$("#tb").on("click", ".d", function() {
var row = $(this).closest('tr').toggleClass("editing");
row.find("td").slice(0, 3).prop("contenteditable", row.hasClass("editing"));
});
$('#btndis').on('click', function() {
//gets table
var oTable = document.getElementById('tb');
//gets rows of table
var rowLength = oTable.rows.length;
//loops through rows
for (i = 0; i < rowLength; i++) {
//gets cells of current row
var oCells = oTable.rows.item(i).cells;
// get your cell info here
var cellVal = oCells.item(1).innerHTML;
$('#ulNames').append('<li>' + cellVal + '</li>');
}
});
});
CSS
.editing {
background: yellow;
}

$("#btndis").click(function() {
$("body").append("ul");
for(var i = 1; i <= $("tr > td").length; i++) {
$("ul").append("li").addClass("li.li-"+i);
$("li.li-"+i).append($("td:nth-child("+i+")").text());
}
}
Explanation :
First, we create the ul to store data. Then, we iterate each tr child (td) with a for loop, we create a li and store data into it. It will be displayed in a list, as asked.

Related

Make table via value

How do I do that JavaScript will print in my HTML page a table via the value the user will choose?
That the JS script:
let numCol = document.getElementById('txtColumns').value;
let numRow = document.getElementById('txtRows').value;
let go = document.getElementById('btn');
let table = document.getElementById('table');
let td = "<td></td>" * numCol;
let tr = ("<tr>" + td + "</tr>") * numRow;
go.addEventListener('click', function(){
table.innerHTML = tr;
})
That the HTML code:
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="style.css">
</head>
<body>
<table class="workTable">
<tr>
<td>
<input type="number" placeholder="Columns Number" id="txtColumns">
</td>
<td>
<input type="number" placeholder="Rows Number" id="txtRows">
</td>
</tr>
<tr>
<td colspan="2" align="center">
<button id="btn">
Print
</button>
</td>
</tr>
<div>
<table id="table">
<!--Here I want to print the table-->
</table>
</div>
</table>
<script src="script.js"></script>
</body>
</html>
At first I thought about that way with the script but its only appear as a NaN and not table...
The following syntax:
let td = "<td></td>" * numCol;
does not produce numCol cells, so the following syntax:
let tr = ("<tr>" + td + "</tr>") * numRow;
does not produce numRow rows also.
So, the whole source code should be:
let go = document.getElementById('btn');
let table = document.getElementById('table');
go.addEventListener('click', () => {
let numCol = document.getElementById('txtColumns').value; //Get the value of txtColumns at the button click moment.
let numRow = document.getElementById('txtRows').value;
let td = "",
tr = "";
for (let i = 0; i < numCol; i++) {
td = td + "<td></td>";
}
for (let i = 0; i < numRow; i++) {
tr = tr + "<tr>" + td + "</tr>";
}
table.innerHTML = tr;
})
<table class="workTable">
<tr>
<td>
<input type="number" placeholder="Columns Number" id="txtColumns">
</td>
<td>
<input type="number" placeholder="Rows Number" id="txtRows">
</td>
</tr>
<tr>
<td colspan="2" align="center">
<button id="btn">
Print
</button>
</td>
</tr>
<div>
<table id="table" border="1">
<!--Here I want to print the table-->
</table>
</div>
</table>

Access to input values created by javascript function

I have a form within a table with Title and description columns and the rows can be added dynamically by a button. I need to access and save the input values in text boxes created by javascript function when saving the form by save button. the input values are later saved on local storage. The saved values are used to repopulate the form in case of unsuccessful validation.
function add_text_input() {
var table = document.getElementById('mytable');
var x = table.rows.length;
table.insertRow(-1).innerHTML = '<tr>' +
'<td> <input type="text" id="title' + x + '" /></td>' +
'<td> <input type="text" id="description' + x + '" /></td></tr>';
}
function save_data() {
var table = document.getElementById('mytable');
var tableRows = table.rows.length;
var data = [];
for (var i = 1; i <= tableRows; i++) {
for (var j = 0; j < 2; j++) {
var title = document.getElementById('title' + i).value;
var desc = document.getElementById('description' + i).value;
var temp = {
title: title,
description: desc
};
data.push(temp);
}
}
window.localStorage.setItem('Table1', JSON.stringify(data));
}
<form>
<table id="mytable">
<tr>
<td> Title </td>
<td> Description </td>
</tr>
</table>
<input type="button" onclick="add_text_input()" value="add row">
<input type="button" onclick="save_data()" value="save">
</form>
did you mean something like this?
$(document).ready(()=>{
$('#container').append('<input id="addedTxt" type="text" />');
$('#addedTxt').val('Test');
$('#saveBtn').on('click', ()=>{
alert($('#addedTxt').val());
});
});
<div id="container">
</div>
<input id="saveBtn" type="button" value="save" />
(using jquery)
https://jsfiddle.net/u6vnxwzc/1/#&togetherjs=rQ2b5IsJQ1
or where is the problem?
In your code why you use the second For loop? I think it is not necessary.
find the working code snippet
https://s.codepen.io/mastersmind/debug/VNyKrY/DqADdKoRXEjA
function add_text_input() {
var table = document.getElementById('mytable');
var x = table.rows.length;
table.insertRow(-1).innerHTML = '<tr>' +
'<td> <input type="text" id="title'+x+'" /></td>'+
'<td> <input type="text" id="description'+x+'" /></td></tr>';
}
function save_data(){
var table = document.getElementById('mytable');
var tableRows = table.rows.length;
var data = [];
for (var i = 1; i <= tableRows-1; i++) {
var title = document.getElementById('title'+ i).value;
var desc = document.getElementById('description'+ i).value;
var temp = {title: title, description: desc};
data.push(temp);
}
window.localStorage.setItem('Table1', JSON.stringify(data));
}
loadData = function(){
let data = JSON.parse(window.localStorage.getItem('Table1'));
for(i=0; i<data.length;i++){
add_text_input();
document.getElementById('title'+ (i+1)).value = data[i].title;
document.getElementById('description'+ (i+1)).value = data[i].description;
}
}
loadData();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form>
<table id="mytable">
<tr>
<td> Title </td>
<td> Description </td>
</tr>
</table>
<input type="button" onclick="add_text_input()" value="add row">
<input type="button" onclick="save_data()" value="save">
</form>
</body>
</html>

Adding buttons to each row of a table to remove said row

just looking for a simple solution on solving this, Consider the the following code:
<!DOCTYPE html>
<html>
<head>
<title>Javascript - Add HTML Table Row </title>
<meta charset="windows-1252">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<form>
<script>
function addRow()
{
// get input values
var name = document.getElementById('name').value;
var currentAge =
document.getElementById('currentAge').value;
var Birthday = document.getElementById('Birthday').value;
var carType = document.getElementById('carType').value;
var Delete = document.getElementById('Delete').value;
var table = document.getElementsByTagName('table')[0];
var newRow = table.insertRow(table.rows.length/2+1);
var cel1 = newRow.insertCell(0);
var cel2 = newRow.insertCell(1);
var cel3 = newRow.insertCell(2);
var cel4 = newRow.insertCell(3);
var cel5 = newRow.insertCell(4);
cel1.innerHTML = name;
cel2.innerHTML = currentAge;
cel3.innerHTML = Birthday;
cel4.innerHTML = carType;
cel5.innerHTML = Delete;
function myFunction(){
var x = document.getElementById("table").rows.length;
document.getElementById("demo").innerHTML = "Found " + x + " tr
elements in the table.";
}
</script>
</form>
</head>
<style>
table, th {
border: 1px solid black;
}
tbody td{
padding: 30px;
}
tbody tr:nth-child(odd){
background-color: #F4BC01;
color: #ABC412;
}
$("")
</style>
<body>
<h2>Basic HTML table</h2> <button onclick="myFunction()">Press me for
elements amount</button>
<p id ="demo"></p>
Name: <input type="text" name="name" id="name" /><br/><br/>
Age: <input type="text" name="currentAge" id="currentAge" /><br/><br/>
Date of Birth <input type="date" name="Birthday" id="Birthday" /><br/>
<button onclick="addRow();">Display</button><br/><br/>
<p>Eye Colour:</p>
<select id="carType">
<option value="ferrari" id="ferrari">Ferrari</option>
<option value="lamborghini" id="lamborghini">Lamborghini</option>
<option value="porsche" id="porsche">Porsche</option>
<option value="bugatti" id="bugatti">Bugatti</option>
<option value="pagani" id="pagani">Pagani</option>
</select>
<table border="1" id="table">
<tr>
<th>Name</th>
<th>Age</th>
<th>Birthday</th>
<th>CarType</th>
<th>Delete Entry
<button id="Delete" onclick="remove_update(event)">delete</button> //this button right here but in each row and not here. should remove said row
</th>
</tr>
</table>
</body>
</html>
What im trying to do is within cel 5 (delete entry) is to add a delete button to each row that is entered into the table that will remove that row but don't know how to go about this. Ideally would like to do this without the use of JQuery if possible, since i've not touched upon it as of yet.
You can use the rowIndex property to delete the row.
function addRow() {
// get input values
var name = document.getElementById('name').value;
var currentAge = document.getElementById('currentAge').value;
var Birthday = document.getElementById('Birthday').value;
var carType = document.getElementById('carType').value;
var table = document.getElementsByTagName('table')[0];
const index = table.rows.length;
var newRow = table.insertRow(index);
newRow.setAttribute('data-index', index);
var cel1 = newRow.insertCell(0);
var cel2 = newRow.insertCell(1);
var cel3 = newRow.insertCell(2);
var cel4 = newRow.insertCell(3);
var cel5 = newRow.insertCell(4);
cel1.textContent = name;
cel2.textContent = currentAge;
cel3.textContent = Birthday;
cel4.textContent = carType;
cel5.innerHTML = '<button onclick="removeRow(this)" type="button" class="delete-button">Delete</button>';
}
function myFunction() {
var x = document.getElementById("table").rows.length;
document.getElementById("demo").innerHTML = "Found " + x + "tr elements in the table.";
}
function removeRow(evt) {
const deleteIndex = evt.parentElement.parentElement.rowIndex;
document.getElementById("table").deleteRow(deleteIndex);
}
table,
th {
border: 1px solid black;
}
tbody td {
padding: 30px;
}
tbody tr:nth-child(odd) {
background-color: #F4BC01;
color: #ABC412;
}
<h2>Basic HTML table</h2> <button onclick="myFunction()">Press me for
elements amount</button>
<p id ="demo"></p>
Name: <input type="text" name="name" id="name" /><br/><br/>
Age: <input type="text" name="currentAge" id="currentAge" /><br/><br/>
Date of Birth <input type="date" name="Birthday" id="Birthday" /><br/>
<button onclick="addRow();">Display</button><br/><br/>
<p>Eye Colour:</p>
<select id="carType">
<option value="ferrari" id="ferrari">Ferrari</option>
<option value="lamborghini" id="lamborghini">Lamborghini</option>
<option value="porsche" id="porsche">Porsche</option>
<option value="bugatti" id="bugatti">Bugatti</option>
<option value="pagani" id="pagani">Pagani</option>
</select>
<table border="1" id="table">
<tr>
<th>Name</th>
<th>Age</th>
<th>Birthday</th>
<th>CarType</th>
<th>Delete</th>
</tr>
</table>
</body>
</html>
What you should be doing is that you set the innerHTML of cel5 to a button, e.g.:
cel5.innerHTML = '<button type="button" class="delete-button">Delete</button>';
Then, you can simply add a click event listener on the table, and check if a click event has emitted from the button element. If it matches, you then delete the closest <tr> element:
document.getElementById('table').addEventListener('click', function(e) {
// Check if click event came from delete button
if (!e.target.classList.contains('delete-button'))
return;
e.target.closest('tr').remove();
});
See proof-of-concept example below:
function addRow() {
// get input values
var name = document.getElementById('name').value;
var currentAge = document.getElementById('currentAge').value;
var Birthday = document.getElementById('Birthday').value;
var carType = document.getElementById('carType').value;
var table = document.getElementsByTagName('table')[0];
var newRow = table.insertRow(table.rows.length / 2 + 1);
var cel1 = newRow.insertCell(0);
var cel2 = newRow.insertCell(1);
var cel3 = newRow.insertCell(2);
var cel4 = newRow.insertCell(3);
var cel5 = newRow.insertCell(4);
cel1.innerHTML = name;
cel2.innerHTML = currentAge;
cel3.innerHTML = Birthday;
cel4.innerHTML = carType;
cel5.innerHTML = '<button type="button" class="delete-button">Delete</button>';
}
function myFunction() {
var x = document.getElementById("table").rows.length;
document.getElementById("demo").innerHTML = "Found " + x + "tr elements in the table.";
}
document.getElementById('table').addEventListener('click', function(e) {
// Check if click event came from delete button
if (!e.target.classList.contains('delete-button'))
return;
e.target.closest('tr').remove();
});
<h2>Basic HTML table</h2> <button onclick="myFunction()">Press me for
elements amount</button>
<p id="demo"></p>
Name: <input type="text" name="name" id="name" /><br/><br/> Age: <input type="text" name="currentAge" id="currentAge" /><br/><br/> Date of Birth <input type="date" name="Birthday" id="Birthday" /><br/>
<button onclick="addRow();">Display</button><br/><br/>
<p>Eye Colour:</p>
<select id="carType">
<option value="ferrari" id="ferrari">Ferrari</option>
<option value="lamborghini" id="lamborghini">Lamborghini</option>
<option value="porsche" id="porsche">Porsche</option>
<option value="bugatti" id="bugatti">Bugatti</option>
<option value="pagani" id="pagani">Pagani</option>
</select>
<table border="1" id="table">
<tr>
<th>Name</th>
<th>Age</th>
<th>Birthday</th>
<th>CarType</th>
<th>Actions</th>
</tr>
</table>
In the head, add a function that understands rows and cells. Call some delete on a parent of a cell (Delete the <tr> in which the <td> is located at). then on the body add to each dynamic button an onClick event and set that function you created earlier ON.
You can use a script like this:
function deleteRow() {
var tableData = event.target.parentNode;
var tableRow = tableData.parentNode;
tableRow.parentNode.removeChild(tableRow);
}
In the button you create (dynamically or fixedly) you should add an onClick event. For example:
<tr>
<td>John Doe</td>
<td>$10,000</td>
<td><input type="submit" value="Delete" id="Delete" onclick="deleteRow()"></td>
</tr>

Adding new row to the table using javascript / jquery

I want to add row to the table on clicking Add button and delete row using Delete button using javascript/jquery. I have tried writing the following code:
<script src="/js/jquery-2.0.3.js"></script>
<script>
/* Javascript for phone numbers*/
$(document).ready(function()
{
var counter = 2;
var count= 4;
$("#add_phone").click(function()
{
alert("whoah it worked");
if(counter>=count)
{
alert("Only " + count + " Phone number allowed.");
return false;
}
var htmlToAppend = '<tr id="pn'+ counter +'"><th>
<select class="phone_no">
<option value="home">home</option>
<option value="Business">Business</option>
<option value="Business2">Business 2</option>
</select>
</th>
<td><input type="text"/></td></tr>';
$("#phone_number").append ( htmlToAppend );
newTableRow.appendTo("#phone_number");
counter++;
});
$("#delete_phone").click(function()
{
if(counter==2)
{
alert("Cannot remove phone number");
return false;
}
counter--;
$("#pn" + counter-1).remove();
});
});
But the alert message alert("whoah it worked"); doesn't get displayed i.e its not entering the function.
<div class="info_type">
Phone numbers <hr>
<table id="phone_number">
<tr id="pn1">
<th>
<select class="phone_no">
<option value="home">home</option>
<option value="Business">Business</option>
<option value="Business2">Business 2</option>
</select>
</th>
<td><input type="text"/></td>
</tr>
</table>
<input type="button" id="add_phone" value="Add"/>
<input type="button" id="delete_phone" value="Delete"/>
</div>
I really want this solution. Can anybody help me??
PS: I am using Ruby on rails
Your string append is not well formed.
var htmlToAppend = '<tr id="pn'+ counter +'"><th><select class="phone_no"> <option value="home">home</option> <option value="Business">Business</option> <option value="Business2">Business 2</option></select> </th><td><input type="text"/></td></tr>';
Working sample in fiddle http://jsfiddle.net/shree/jNA4x/
try to rewrite htmlToAppend variable with a \n\ in the end of each line
demo
You can't have line breaks in your htmlToAppend variable,
var htmlToAppend = '<tr id="pn'+ counter +'"><th><select class="phone_no"><option value="home">home</option><option value="Business">Business</option><option value="Business2">Business 2</option></select></th><td><input type="text"/></td></tr>';
$("#phone_number").append ( htmlToAppend );
Example Code
A common pitfall for me as well.
increment the counter you did not increments it.
for more help use like the below example.
<html>
<h1>Add remove dynamically</h1>
<head>
<title></title>
</head>
<body>
Living in:
<table id="purchaseItems" name="purchaseItems" style="display: inline-table;">
<tr id="tr_1">
<td>
<input type="text" name="living_1" class="tbDescription next" required />
</td>
<td>
<input type="text" name="biggest_1" class="next" required />
</td>
<td>
<input type="text" name="nextbiggest_1" class="nextRow" required />
</td>
<td>
<input type="button" name="addRow[]" id="remove_1" class="removeRow" value='-' />
</td>
<td>
<input type="button" name="addRow[]" id="add_1" class="add" value='+' />
</td>
</tr>
</table>
</body>
</html>
<script type="text/javascript">
$("#remove_1").hide();
$(document).ready(function () {
$(document).on('click', '#purchaseItems .add', function () {
var total_row = $('#purchaseItems tr').length;
var rows = $('#purchaseItems tr').length+1;
if(total_row < 5)
{
// clear the values
$('#purchaseItems tr:last').after('<tr id="tr_'+rows+'"><td><input type="text" name="living_'+rows+'" id="living_'+rows+'" class="tbDescription next"></td><td><input type="text" name="biggest_'+rows+'" id="biggest_'+rows+'" class="next"></td><td><input type="text" name="nextbiggest_'+rows+'" id="nextbiggest_'+rows+'" class="nextRow"></td><td><input type="button" name="addRow[]" id="remove_'+rows+'" class="removeRow" value="-"></td><td><input type="button" name="addRow[]" id="add_'+rows+'" class="add" value="+"></td></tr>');
$(".add").hide();
$(".removeRow").show();
$("#add_"+rows).show();
}
else
{
alert("Maximum limit reached.")
}
});
$(document).on('keypress', '#purchaseItems .next', function (e) {
if (e.which == 13) {
var v = $(this).index('input:text');
var n = v + 1;
$('input:text').eq(n).focus();
//$(this).next().focus();
}
});
$(document).on('keypress', '#purchaseItems .nextRow', function (e) {
if (e.which == 13) {
$(this).closest('tr').find('.add').trigger('click');
$(this).closest('tr').next().find('input:first').focus();
}
});
$(document).on('click', '#purchaseItems .removeRow', function () {
var total_row = $('#purchaseItems tr').length;
if ($('#purchaseItems .add').length > 1) {
$(this).closest('tr').remove();
var last_tr_id = $('#purchaseItems tr:last').attr("id").split("_")[1];
$("#add_"+last_tr_id).show();
}
if ($('#purchaseItems .add').length == 1) {
$(".removeRow").hide();
}
});
});
</script>
Try this way using Jquery
<form id="myForm">
<div class="clonedInput">
<input type="text" class="phone_oa" id="textPhone1" name="input1" placeholder="Enter phone number" style="width: 110px;" />
<input type="button" name="btnDelete1" class="btnDel" value="Remove" disabled="disabled" />
</div>
<div id="addDelButtons" style="margin-top: 10px;">
<button type="button" id="btnAdd" class="btn" >Add Another Number</button>
</div>
</form>
Script
var inputs = 1;
$('#btnAdd').click(function() {
$('.btnDel:disabled').removeAttr('disabled');
var c = $('.clonedInput:first').clone(true);
c.children(':text').attr('name','input'+ (++inputs) ).val('');
c.children(':text').attr('id','textPhone'+ (inputs) ).val('');
c.children(':button').attr('name','btnDelete'+ (inputs) );
$('.clonedInput:last').after(c);
$('#btnAdd').attr('disabled',($('.clonedInput').length > 4));
});
$('.btnDel').click(function() {
if (confirm('Confirm delete?')) {
--inputs;
$(this).closest('.clonedInput').remove();
$('.btnDel').attr('disabled',($('.clonedInput').length < 2));
$('#btnAdd:disabled').removeAttr('disabled');
fixNames();
}
});
function fixNames(){
var i = inputs;
while(i--) {
$('input:text')[i].name = 'input'+ (i+1);
$('input:button')[i].name = 'btnDelete'+ (i+1);
}
}
DEMO

jquery live function for adding/removing rows

I' m trying to enable adding/deleting rows to/from table using folowing code:
Script:
$(document).ready(function() {
$('#btnAdd').live('click', function() {
var name = $('#txtName').val();
var name2 = $('#txtName2').val();
$("#tbNames tr:last").append("<tr><td>" + name + "</td><td>" + name2 + "</td><td><simg ssrc='delete.gif' class='delete' height='15' /></td></tr>");
});
$('#tbNames td img.delete').live('click',function() {
$(this).parent().parent().remove();
});
});
HTML
<input id="txtName" type="text" />
<input id="txtName2" type="text" />
<input id="btnAdd" type="button" value="Add" />
<table id="tbNames" >
<tr>
<td>Name</td>
<td>Name2</td>
<td>Delete</td>
</tr>
<tr>
<td>Bingo</td>
<td>Tingo</td>
<td><simg ssrc="Delete.gif" height="15" class="delete" /></td>
</tr>
</table>
Adding works fine, but deleting does not.
It deletes all dynamically added rows behind the clicked one.
I changed the add function from "append" to "after"
$("#tbNames tr:last").after("<tr><td>" + name + "</td><td>" + name2 + "</td><td><img src='delete.gif' class='delete' height='15' /></td></tr>");
And corrected the markup cos it said "simg" instead of "img"
So the compelte solution is
<script type="text/javascript">
$(document).ready(function() {
$('#btnAdd').live
('click',
function() {
var name = $('#txtName').val();
var name2 = $('#txtName2').val();
$("#tbNames tr:last").after("<tr><td>" + name + "</td><td>" + name2 + "</td><td><img src='delete.gif' class='delete' height='15' /></td></tr>");
}
);
$('#tbNames td img.delete').live('click',function() { $(this).parent().parent().remove(); });
}
);
</script>
<input id="txtName" type="text" />
<input id="txtName2" type="text" />
<input id="btnAdd" type="button" value="Add" />
<table id="tbNames" >
<tr>
<td>Name</td>
<td>Name2</td>
<td>Delete</td>
</tr>
<tr>
<td>Bingo</td>
<td>Tingo</td>
<td><img src="Delete.gif" height="15" class="delete" /></td>
</tr>
</table>
You are appending a TR to a TR, it should be appended to the tbody (or table) of the table. or .after() the TR.
$("#tbNames tbody").append("<tr><td>" + name + "</td><td>" + name2 + "</td><td><img src='delete.gif' class='delete' height='15' /></td></tr>")
Also, you should probably specify which parent you are looking for .closest() makes that pretty easy:
$("#tbNames td img.delete").live('click', function() {
$(this).closest('tr').remove();
});

Categories

Resources