How to edit and update values in a dynamic table using JQuery? - javascript

Below is code for adding inputs into a dynamic table and for each row an edit button is also generated, my question is how would I pass the values in the table back into the input fields when I click on the edit button of a specific row and then update the specific row based on the changes made to the values in the input fields when i click on the update row button.
$("#btnAdd").on('click', function() {
let row = '<tr> <td>' + $("#insert-name").val() + '</td> <td>' + $("#insert-surname").val() + '</td> <td>' + "edit" + '</td> </tr>'
$('tbody').append(row);
$('td:contains("edit")').html("<button type='button'>" + "edit" + "</button>").on('click', function() {
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<div>
<label for="insert-name">Name:</label>
<input type="text" id="insert-name">
</div>
<div>
<label for="insert-surname">Surname:</label>
<input type="text" id="insert-surname">
</div>
</form>
<button type="button" id="btnAdd">Add to Table</button>
<button type="button" id="btnUpdate">Update row</button>
<table>
<thead>
<tr>
<th scope="col">Name</th>
<th scope="col">Surname</th>
<th scope="col">Edit</th>
</tr>
</thead>
<tbody id="tbody"></tbody>
</table>

Check this (Read JS comments)
$("#btnAdd").on('click', function() {
let row = '<tr> <td>' + $("#insert-name").val() + '</td> <td>' + $("#insert-surname").val() + '</td> <td>' + "edit" + '</td> </tr>'
$('tbody').append(row);
$('td:contains("edit")').html("<button type='button' class='edit'>" + "edit" + "</button>").on('click', function() {
});
});
//--------------------------------------------------------//
$(document).on("click",".edit",function(){ // Click function on class '.edit' (your appended button)
var name = $(this).parents("tr").find("td:eq(0)").html(); // Search for 'name' depending on this edit button parent.
var surname = $(this).parents("tr").find("td:eq(1)").html(); // Search for 'surname' depending on this edit button parent.
var rowNumber = $(this).parents("tr").index() // Get index of this edit button parent 'row'.
$("#edit-name").val(name); // Read the name and put it in '#edit-name' inside '.editArea'.
$("#edit-surname").val(surname); // Read the surname and put it in '#edit-surname' inside '.editArea'.
$(".saveEdits").attr("for",rowNumber); // Store this row index as attribute in '.saveEdits' button to be able to pass it to the other function that saves data.
$(".editArea").fadeIn(300); // Show the edit box.
});
$(".saveEdits").click(function(){ // Function to save data
var rowNumber = parseInt($(this).attr("for")); // Get the row number that we already define in the prev. function.
$('td:eq(0)','tr:eq('+(rowNumber+1)+')').html($("#edit-name").val()); // Update 'td' content depending on the 'tr' index.
$('td:eq(1)','tr:eq('+(rowNumber+1)+')').html($("#edit-surname").val()); // Update 'td' content depending on the 'tr' index.
});
$(".cancel").click(function(){ // Button to cancel edit.
$("#edit-name").val(""); // Empty value.
$("#edit-surname").val(""); // Empty value.
$(".saveEdits").attr("for","0"); // Set row number to zero.
$(".editArea").fadeOut(300); // Hide edit area.
});
.editArea{
display:none;
background:#fff;
padding:10px;
border:1px solid #ddd;
border-radius:5px;
box-shadow:0 0 0 #000;
width:50%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<form>
<div>
<label for="insert-name">Name:</label>
<input type="text" id="insert-name">
</div>
<div>
<label for="insert-surname">Surname:</label>
<input type="text" id="insert-surname">
</div>
</form>
<button type="button" id="btnAdd">
Add to Table
</button>
<table>
<thead>
<tr>
<th scope="col">Name</th>
<th scope="col">Surname</th>
<th scope="col">Edit</th>
</tr>
</thead>
<tbody id="tbody">
</tbody>
</table>
<div class='editArea'>
<label>Name</label>
<input type="text" id="edit-name">
<br>
<label>Surname</label>
<input type="text" id="edit-surname">
<hr>
<button class='saveEdits' for="0">Save edits</button>
<button class='cancel'>Cancel</button>
</div>
</body>
</html>

Here is a solution with edit row in just within existent inputs
var counter = 0;
var current_row = null;
$("#btnAdd").on('click', function() {
if (current_row == null) {
if ( $("#insert-surname").val().length && $("#insert-name").val().length ) {
let row = '<tr data-row="'+counter+'"> <td>' + $("#insert-name").val() + '</td> <td>' + $("#insert-surname").val() + '</td> <td>' + "edit" + '</td> </tr>'
$('tbody').append(row);
counter++;
}
} else {
var select_row = $('tr[data-row='+current_row+']');
let cells = $(select_row).find('td');
$(cells[0]).text($("#insert-name").val());
$(cells[1]).text($("#insert-surname").val());
}
clear_input();
$('td:contains("edit")').html("<button type='button'>" + "edit" + "</button>").on('click', function() {
let cells = $(this).parents('tr').find('td');
$("#insert-name").val($(cells[0]).text());
$("#insert-surname").val($(cells[1]).text());
current_row = $(this).parents('tr').data('row');
});
});
$('#btnCancel').on("click", () => clear_input());
function clear_input() {
current_row = null;
$("#insert-name").val('');
$("#insert-surname").val('');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<div>
<label for="insert-name">Name:</label>
<input type="text" id="insert-name">
</div>
<div>
<label for="insert-surname">Surname:</label>
<input type="text" id="insert-surname">
</div>
</form>
<button type="button" id="btnAdd">Add to Table</button>
<button type="button" id="btnCancel">Cancel</button>
<table id='data-table'>
<thead>
<tr>
<th scope="col">Name</th>
<th scope="col">Surname</th>
<th scope="col">Edit</th>
</tr>
</thead>
<tbody id="tbody"></tbody>
</table>

Now let's begin with what wrong with the OP's solution. OP is trying to add event listner to an element which hasn't been created yet. The way we listen to dynamic data is through event delegation.
So for this:
<tbody>
// dynamic <tr></tr>
</tbody>
We would attach our listener to some parent of it (not necessarily the closest parent) i.e., <tbody> in this case which is part of the dom when we run our js code.
I'm sure that there are various ways of doing it, but I gave it a shot by sticking close to your actual solution. Check it out:
function addToTable() {
// insertion into row
let name = $("#insert-name").val();
let surname = $("#insert-surname").val();
let row = `<tr>
<td>${name}</td>
<td>${surname}</td>
<td><button>Edit</button></td>
</tr>`;
$('#tbody').append(row);
// clearing input fields
$("#insert-name").val("");
$("#insert-surname").val("");
}
function editTable() {
let name = $("#insert-name").val();
let surname = $("#insert-surname").val();
// looking for tr with "active" class
let row = $("#tbody tr.active");
let rowArr = row[0].children;
rowArr[0].innerHTML = name;
rowArr[1].innerHTML = surname;
row[0].classList.remove("active");
// clearing input fields
$("#insert-name").val("");
$("#insert-surname").val("");
}
$("#btnAdd").on('click', function() {
let isEdit = $("#btnAdd").hasClass("edit");
if (isEdit) {
editTable();
} else {
addToTable();
}
// remove class "edit"
$("tbody").removeClass("edit");
});
// Adding event listner to the parent (event delegation)
$("#tbody").on('click', function(e) {
$("#btnAdd").addClass("edit");
// pass table data to input fields
let row = e.target.closest("tr");
row.classList.add("active");
let rowArr = row.children;
$("#insert-name").val(rowArr[0].innerHTML);
$("#insert-surname").val(rowArr[1].innerHTML);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<form>
<div>
<label for="insert-name">Name:</label>
<input type="text" id="insert-name">
</div>
<div>
<label for="insert-surname">Surname:</label>
<input type="text" id="insert-surname">
</div>
</form>
<button type="button" id="btnAdd">
Add to Table
</button>
<table>
<thead>
<tr>
<th scope="col">Name</th>
<th scope="col">Surname</th>
<th scope="col">Edit</th>
</tr>
</thead>
<tbody id="tbody">
</tbody>
</table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</body>
</html>

Related

jquery add column and sum/total the table column

I’ve searched and consulted a lot of code but nothing is helping me to fix my problem.
What I have is just "add rows", but I want also the sum after adding the rows.
Here is a part of my code that adds a row to a table:
Code for adding rows
$(document).ready(function () {
$(".add-row").click(function () {
var name = $("#name").val();
var email = $("#email").val();
var markup = "<tr><td style='text-align:center'><input type='checkbox' name='record'></td><td>" + email + "</td><td class='sum_me' style='text-align: right;'>" + name + "</td></tr>";
$("table tbody").append(markup);
});
});
Html
<table id="countit">
<thead>
<tr>
<th width=50px>Delete</th>
<th width=150px style="text-align: center;">Inpayment of:</th>
<th width=50px style="text-align: center;">AMOUNT :</th>
</tr>
</thead>
<tbody>
<tr></tr>
</tbody>
</table>
<input type="button" class="btn-success" value="Save Transaction" style="width: 150px; float: right;">
<br>
<br>
Create a function that sums the values and shows the result. call it after adding the row to the table.
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
function updateSum(){
var sum = 0;
$('.sum_me').each(function(item, index){
sum = sum + $(item).text();
});
$('#total').text(sum);
}
$(document).ready(function(){
$(".add-row").click(function(){
var name = $("#name").val(); // input text
var email = $("#email").val(); // input text
var markup = "<tr><td style='text-align:center'><input type='checkbox' name='record'></td><td>" + email + "</td><td class='sum_me' style='text-align: right;'>" + name + "</td></tr>";
$("table tbody").append(markup);
updateSum();
});
});
</script>
You can use tfooter after the tbody to hold this total value
<table id="countit">
<thead>
<tr>
<th width=50px>Delete</th>
<th width=150px style="text-align: center;">Inpayment of:</th>
<th width=50px style="text-align: center;">AMOUNT :</th>
</tr>
</thead>
<tbody>
<tr>
</tr>
</tbody>
<tfoot>
<tr><td></td><td></td><td id="total"></td></tr>
</tfoot>
</table>
<input type="button" class="btn-success" value="Save Transaction" style="width: 150px; float: right;">

Dynamically add row with jQuery

I have an application that integrated with barcode scanner, like this:
I have made a row dynamically with this snippet of code:
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<div class="container" align="top" style="margin-top: 0px;">
<h1 align="center">
Barcode: <br><input type="text" id="myHeader" value="5555">
</h1>
<table id="myTable" class=" table order-list">
<thead>
<tr>
<td>Barcode</td>
<td>Item</td>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
<tr>
<td colspan="7" style="text-align: left;">
<div align="right">
<p style="color: black;margin-right: 90px;">9.999.999</p>
</div>
<input type="button" class="btn btn-lg btn-block " id="addrow" value="Add Row" style="border-color: black;" />
</td>
</tr>
<tr>
</tr>
</tfoot>
</table>
</div>
and here is the code that I wrapped with script tag:
<script >
$(document).ready(function() {
var counter = 0;
$("#addrow").on("click", function() {
var newRow = $("<tr>");
var cols = "";
cols += '<td><input type="text" disabled value="123123123" class="form-control" name="name' + counter + '"/></td>';
cols += '<td><input type="text" disabled value="Sekop" class="form-control" name="mail' + counter + '"/></td>';
cols += '<td><input type="button" class="ibtnDel btn btn-md btn-danger " value="Delete"></td>';
newRow.append(cols);
$("table.order-list").append(newRow);
counter++;
});
$("table.order-list").on("click", ".ibtnDel", function(event) {
$(this).closest("tr").remove();
counter -= 1
});
});
function calculateRow(row) {
var price = +row.find('input[name^="price"]').val();
}
function calculateGrandTotal() {
var grandTotal = 0;
$("table.order-list").find('input[name^="price"]').each(function() {
grandTotal += +$(this).val();
});
$("#grandtotal").text(grandTotal.toFixed(2));
} </script>
But the code above just add the row only when I clicked the Add Row button.
What I want for now is, when I scan a barcode with a barcode scanner, the row automatically added follow the scanned barcode result.
In this case it will be: "When the value on barcode on the header changed ( <h1 align="center">Barcode: 123123123</h1> , the result is same when I clicked the Add Row button.
So, please refer any approach, tutorial or example code how to do that, it would be very appreciated :)
For additional information: The purpose of this app is for cashier app on a store, like when the cashier scan a product, the result automatically appear on the app. And I developing it using Python Flask.
You have to listen to the changes made in the element. You can try with MutationObserver
$(document).ready(function() {
var counter = 0;
$("#addrow").on("click", function() {
var newRow = $("<tr>");
var cols = "";
cols += '<td><input type="text" disabled value="123123123" class="form-control" name="name' + counter + '"/></td>';
cols += '<td><input type="text" disabled value="Sekop" class="form-control" name="mail' + counter + '"/></td>';
cols += '<td><input type="button" class="ibtnDel btn btn-md btn-danger " value="Delete"></td>';
newRow.append(cols);
$("table.order-list").append(newRow);
counter++;
});
$("table.order-list").on("click", ".ibtnDel", function(event) {
$(this).closest("tr").remove();
counter -= 1
});
});
function calculateRow(row) {
var price = +row.find('input[name^="price"]').val();
}
function calculateGrandTotal() {
var grandTotal = 0;
$("table.order-list").find('input[name^="price"]').each(function() {
grandTotal += +$(this).val();
});
$("#grandtotal").text(grandTotal.toFixed(2));
}
// Listen to the changes in the header element and add row
var target = document.querySelector('#myHeader');
setTimeout(function() {
target.textContent = "New Barcode: XXXXXXXXX"; // change text after 2 seconds
}, 2000)
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
$("#addrow").trigger("click"); // trigger the click event to add row if the header text is changed
});
});
var config = {
attributes: true,
childList: true,
characterData: true
};
observer.observe(target, config);
// otherwise
observer.disconnect();
observer.observe(target, config);
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<div class="container" align="top" style="margin-top: 0px;">
<h1 align="center" id="myHeader">Barcode: 123123123</h1>
<table id="myTable" class=" table order-list">
<thead>
<tr>
<td>Barcode</td>
<td>Item</td>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
<tr>
<td colspan="7" style="text-align: left;">
<div align="right">
<p style="color: black;margin-right: 90px;">9.999.999</p>
</div>
<input type="button" class="btn btn-lg btn-block " id="addrow" value="Add Row" style="border-color: black;" />
</td>
</tr>
<tr>
</tr>
</tfoot>
</table>
</div>
Update: The updated question indicates that you can trigger the click event on blur event of the barcode input element:
$(document).ready(function() {
var counter = 0;
$("#addrow").on("click", function() {
var newRow = $("<tr>");
var cols = "";
var barcode = $("#myHeader").val().trim();// take the current barcode value
cols += '<td><input type="text" disabled value= '+ barcode +' class="form-control" name="name' + counter + '"/></td>';
cols += '<td><input type="text" disabled value="Sekop" class="form-control" name="mail' + counter + '"/></td>';
cols += '<td><input type="button" class="ibtnDel btn btn-md btn-danger " value="Delete"></td>';
newRow.append(cols);
$("table.order-list").append(newRow);
counter++;
});
$("table.order-list").on("click", ".ibtnDel", function(event) {
$(this).closest("tr").remove();
counter -= 1
});
});
function calculateRow(row) {
var price = +row.find('input[name^="price"]').val();
}
function calculateGrandTotal() {
var grandTotal = 0;
$("table.order-list").find('input[name^="price"]').each(function() {
grandTotal += +$(this).val();
});
$("#grandtotal").text(grandTotal.toFixed(2));
}
// Add new row by triggering the click event on focus out
var target = document.querySelector('#myHeader');
target.addEventListener('blur', function(){
$("#addrow").trigger("click");
});
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<div class="container" align="top" style="margin-top: 0px;">
Barcode: <br><input type="text" id="myHeader" value="5555">
<table id="myTable" class=" table order-list">
<thead>
<tr>
<td>Barcode</td>
<td>Item</td>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
<tr>
<td colspan="7" style="text-align: left;">
<div align="right">
<p style="color: black;margin-right: 90px;">9.999.999</p>
</div>
<input type="button" class="btn btn-lg btn-block " id="addrow" value="Add Row" style="border-color: black;" />
</td>
</tr>
<tr>
</tr>
</tfoot>
</table>
</div>
$('#myTable tbody').append(newRow)
I think you have problem with your jQuery selector.
Try the code shown above - hope it works for you.

Why does it keep on duplicating the current row I’m updating?

So I’ve been encountering another problem from the last code I’ve posted: it keeps on duplicating the current row I’m updating. The code for updating the row is fine, it stays at the same position not below all the rows, but the only problem is that it duplicates the current row I’m updating. This is my last problem and my code is done. Hope y’all could help me.
function remove(deletelink) {
$(deletelink).closest("tr").remove();
if ($("tbody").find("tr").length == 0) {
$("tbody").append("<tr id='nomore'><td colspan='4'>No more records.</td></tr>");
}
return false;
}
function edit(editlink) {
var name = $(editlink).closest("tr").find("td.name").text();
var course = $(editlink).closest("tr").find("td.course").text();
$("#name").val(name);
$("#course").val(course);
$("#button").val("SAVE");
}
$(document).ready(function() {
let row = null;
//DELETE RECORD
$(".delete").click(function() {
remove(this);
});
//EDIT RECORD
$(".edit").click(function() {
row = $(this).closest('tr');
$('#name').val(row.find('td:eq(0)').text())
$('#course').val(row.find('td:eq(1)').text())
edit(this);
});
$("#button").click(function() {
var name = $("#name").val();
var course = $("#course").val();
//REMOVE "NO MRORE RECORDS WHEN ADDING"
if ($("tbody").find("tr#nomore").length > 0) {
$("tbody").html("");
}
//ADD RECORD
$("tbody").append("<tr><td class='name'>" + name + "</td><td class='course'>" + course + "</td><td><a href='#' class='edit'>Edit</a></td><td><a href='#' class='delete'>Delete</a></td></tr>");
//UPDATE RECORD
if (row) {
row.find('td:eq(0)').text($('#name').val());
row.find('td:eq(1)').text($('#course').val());
$('#name').val('');
$('#course').val('');
}
//DELETE THE NEWLY UPDATED RECORD
$(".delete").click(function() {});
$(".delete").click(function() {
remove(this);
});
//EDIT RECORD AFTER DELETING
$(".edit").click(function() {});
$(".edit").click(function() {
edit(this);
});
});
});
<!DOCTYPE html>
<html>
<head>
<title>Sample jQuery</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<input type="text" id="name" placeholder="Name" />
<input type="text" id="course" placeholder="Course" />
<input type="button" id="button" value="ADD" />
<br /><br />
<table border="1" cellpadding="3">
<thead>
<tr>
<th>Name</th>
<th>Course</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td class="name">Joaquin</td>
<td class="course">BSIT</td>
<td>
Edit
</td>
<td>
Delete
</td>
</tr>
<tr>
<td class="name">Jump</td>
<td class="course">BSIT</td>
<td>
Edit
</td>
<td>
Delete
</td>
</tr>
<tr>
<td class="name">Ersan</td>
<td class="course">BSHRM</td>
<td>
Edit
</td>
<td>
Delete
</td>
</tr>
<tr>
<td class="name">Laree</td>
<td class="course">BSIT</td>
<td>
Edit
</td>
<td>
Delete
</td>
</tr>
</tbody>
</table>
</body>
</html>
You're using the same button for both add and update. When you are updating, it is calling the append part, which you don't want to do:
//ADD RECORD
$("tbody").append("<tr><td class='name'>" + name + "</td><td class='course'>" + course + "</td><td><a href='#' class='edit'>Edit</a></td><td><a href='#' class='delete'>Delete</a></td></tr>");
You need to check if you are adding or editing before this append.
If the record is going to be updated then no need to add it in table.
Modified code:
//UPDATE RECORD
if (row) {
row.find('td:eq(0)').text($('#name').val());
row.find('td:eq(1)').text($('#course').val());
$('#name').val('');
$('#course').val('');
}
else
{
//ADD RECORD
$("tbody").append("<tr><td class='name'>" + name + "</td><td class='course'>" + course + "</td><td><a href='#' class='edit'>Edit</a></td><td><a href='#' class='delete'>Delete</a></td></tr>");
}
Full code:
function remove(deletelink) {
$(deletelink).closest("tr").remove();
if ($("tbody").find("tr").length == 0) {
$("tbody").append("<tr id='nomore'><td colspan='4'>No more records.</td></tr>");
}
return false;
}
function edit(editlink) {
var name = $(editlink).closest("tr").find("td.name").text();
var course = $(editlink).closest("tr").find("td.course").text();
$("#name").val(name);
$("#course").val(course);
$("#button").val("SAVE");
}
$(document).ready(function() {
let row = null;
//DELETE RECORD
$(".delete").click(function() {
remove(this);
});
//EDIT RECORD
$(".edit").click(function() {
row = $(this).closest('tr');
$('#name').val(row.find('td:eq(0)').text())
$('#course').val(row.find('td:eq(1)').text())
edit(this);
});
$("#button").click(function() {
var name = $("#name").val();
var course = $("#course").val();
//REMOVE "NO MRORE RECORDS WHEN ADDING"
if ($("tbody").find("tr#nomore").length > 0) {
$("tbody").html("");
}
//UPDATE RECORD
if (row) {
row.find('td:eq(0)').text($('#name').val());
row.find('td:eq(1)').text($('#course').val());
$('#name').val('');
$('#course').val('');
}
else
{
//ADD RECORD
$("tbody").append("<tr><td class='name'>" + name + "</td><td class='course'>" + course + "</td><td><a href='#' class='edit'>Edit</a></td><td><a href='#' class='delete'>Delete</a></td></tr>");
}
//DELETE THE NEWLY UPDATED RECORD
$(".delete").click(function() {});
$(".delete").click(function() {
remove(this);
});
//EDIT RECORD AFTER DELETING
$(".edit").click(function() {});
$(".edit").click(function() {
edit(this);
});
});
});
<!DOCTYPE html>
<html>
<head>
<title>Sample jQuery</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<input type="text" id="name" placeholder="Name" />
<input type="text" id="course" placeholder="Course" />
<input type="button" id="button" value="ADD" />
<br /><br />
<table border="1" cellpadding="3">
<thead>
<tr>
<th>Name</th>
<th>Course</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td class="name">Joaquin</td>
<td class="course">BSIT</td>
<td>
Edit
</td>
<td>
Delete
</td>
</tr>
<tr>
<td class="name">Jump</td>
<td class="course">BSIT</td>
<td>
Edit
</td>
<td>
Delete
</td>
</tr>
<tr>
<td class="name">Ersan</td>
<td class="course">BSHRM</td>
<td>
Edit
</td>
<td>
Delete
</td>
</tr>
<tr>
<td class="name">Laree</td>
<td class="course">BSIT</td>
<td>
Edit
</td>
<td>
Delete
</td>
</tr>
</tbody>
</table>
</body>
</html>
You are getting the duplication because your save action has an append in it
//ADD RECORD
$("tbody").append("<tr><td class='name'>" + name + "</td><td class='course'>" + course + "</td><td><a href='#' class='edit'>Edit</a></td><td><a href='#' class='delete'>Delete</a></td></tr>");
Use the row variable you are setting as an if condition to see if you should add or edit
if(!row){
$("tbody").append("<tr><td class='name'>" + name + "</td><td class='course'>" + course + "</td><td><a href='#' class='edit'>Edit</a></td><td><a href='#' class='delete'>Delete</a></td></tr>");
} else {
row.find('td:eq(0)').text($('#name').val());
row.find('td:eq(1)').text($('#course').val());
$('#name').val('');
$('#course').val('');
//set row back to null
row=null;
}
You are also creating new click handlers for all your rows each time "Save" is clicked, not just adding a new one to a new row. This will cause duplicated event calls for a single click. Use event delegation and you will only need to setup click handlers once:
$("table").on('click','.delete',function() {
remove(this);
});
//EDIT RECORD
$("table").on('click','.edit',function() {
row = $(this).closest('tr');
$('#name').val(row.find('td:eq(0)').text())
$('#course').val(row.find('td:eq(1)').text())
edit(this);
});

How to get checked checkbox table value in jquery

In my table I have 2 rows please see my screen shot,suppose I click first check box means I want to take that id ** and **to_area value in jquery how can do this,I tried but I can not get please help some one
$(document).ready(function() {
$('#chemist_allotment_btn').click(function() {
if ($('#chemist_allotment_form').valid()) {
$.ajax({
url: 'update_chemist_bulk_transfer.php',
type: 'POST',
data: $('form#chemist_allotment_form').serialize(),
success: function(data) {
var res = jQuery.parseJSON(data); // convert the json
console.log(res);
if (res['status'] == 1) {
var htmlString = '';
$.each(res['data'], function(key, value) {
htmlString += '<tr>';
htmlString += ' <td class="sorting_1"><div class="checkbox-custom checkbox-success"><input type="checkbox" id="checkboxExample3" name="getchemist" class="getchemist" value="' + value.id + '"><label for="checkboxExample3"></label></div></td>';
htmlString += '<td>' + value.id + '</td>';
htmlString += '<td>' + value.name + '</td>';
htmlString += '<td>' + value.area + '</td>';
htmlString += '<td>' + value.to_area + '</td>';
htmlString += '<td>' + value.address + '</td>';
htmlString += '</tr>';
});
$('#SampleDT tbody').empty().append(htmlString);
$('#get_to_area').click(function() {
var id = $('input[name=getchemist]:checked').val();
if ($(".getchemist").prop('checked') == true) {
alert(id);
alert(value.to_area);
} else {
alert('Please Check');
}
});
} else {
$('#SampleDT tbody').empty().append('No Datas Found');
}
},
});
return false;
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="well white">
<table id="SampleDT" class="datatable table table-hover table-striped table-bordered tc-table">
<thead>
<tr>
<th>Select</th>
<th>Id</th>
<th>Doctor Name</th>
<th>From Area</th>
<th>To Area</th>
<th>Address</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<center>
<div class="form-group">
<button type="button" class="btn btn-primary" style="text-align:left;" id="get_to_area">Transfer Area</button>
</div>
</center>
</div>
Firstly, add classes to each <td>, like <td class='id'>[Your id]</td>
Similarly for all the elements doctor-name, to-area, etc and a class to each <tr> like row-select
Somewhat like this:
<tr class="row-select">
<td class="select">...</td>
<td class="id">...</td>
<td class="to-area">...</td>
.
.
.
</tr>
Use jQuery like this:
$('.row-select').click(function(){
var id,toArea,checkBox;
id = $(this).find('.id').html(); //get the ID field
toArea = $(this).find('.to-area').html(); //get the to-area field
checkBox = $(this).find('.select > input');
checkbox.prop('checked',!checkbox.prop('checked'));
})
This code will get you he value no mater where you click on the row, and also invert the selection on the checkbox
To get the values of rows selected when the form is submitted run a loop like this
$('.row-select input:checked').each(function(){
var id,toArea,checkBox;
id = $(this).closest('tr').find('.id').html(); //get the ID field
toArea = $(this).closest('tr').find('.to-area').html(); //get the to-area field
})
EDIT
All together:
$(document).ready(function() {
$('#btnSubmit').click(function() {
$('.row-select input:checked').each(function() {
var id, name;
id = $(this).closest('tr').find('.id').html();
name = $(this).closest('tr').find('.name').html();
alert('ID: ' + id + " | Name: " + name);
})
})
$('#btnSelectAll').click(function() {
$('.row-select input').each(function() {
$(this).prop('checked', true);
})
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border=1>
<tr class="row-select">
<td class="check">
<input type="checkbox" />
</td>
<td class="id">12</td>
<td class="name">Jones</td>
</tr>
<tr class="row-select">
<td class="check">
<input type="checkbox" />
</td>
<td class="id">10</td>
<td class="name">Joseph</td>
</tr>
</table>
<button id="btnSelectAll">Select all</button>
<button id="btnSubmit">Get Value</button>
Process step-by-step:
Give the td you need some classes (from-a & to-a);
Initialize an empty array all (we'll store the data inside it later on);
Create a function that is triggered by the checkbox change
Inside the function you need to know which checkbox has changed, what's the state of it, what tr does it belong to and at the end what are the TO AREA and FROM AREA values.
If the state = checked we will add the values to the all (our small data storage);
If the state = not-checked we will remove the value from the all array;
Finally when we are done with selecting and deselecting rows by pressing the button we can get the values of the selected rows.
var all = [];
$('input[type="checkbox"]').change(function(){
var checkbox = $(this);
var state = checkbox.prop('checked');
var tr = checkbox.parents('tr');
var from = tr.children('.from-a').text();
var to = tr.children('.to-a').text();
if(state){
all.push(from + ' -> ' + to);
}else{
var index = all.indexOf(from + ' -> ' + to);
all.splice(index, 1);
}
})
$('#get_to_area').click(function(){
alert(all);
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div class="well white">
<table id="SampleDT" class="datatable table table-hover table-striped table-bordered tc-table">
<thead>
<tr>
<th>Select</th>
<th>Id</th>
<th>Doctor Name</th>
<th>From Area</th>
<th>To Area</th>
<th>Address</th>
</tr>
</thead>
<tbody>
<tr id="1">
<td><input type="checkbox"></td>
<td>1</td>
<td>Nick</td>
<td class="from-a">Kosur</td>
<td class="to-a">Nath Pari</td>
<td>Address</td>
</tr>
<tr id="2">
<td><input type="checkbox"></td>
<td>2</td>
<td>John</td>
<td class="from-a">Rusok</td>
<td class="to-a">iraP htaN</td>
<td>sserddA</td>
</tr>
</tbody>
</table>
<center>
<div class="form-group">
<button style="text-align:left;" id="get_to_area">Transfer Area</button>
</div>
</center>
</div>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</body>
</html>
This is just the basic concept, you can modify it to suit your needs, I'll be happy to help you if you get stuck.
You can also use this fiddle:
In JS:
$('#get_to_area').click(function () {
var id = $('input[name=getchemist]:checked').val();
if ($('input[name=getchemist]').is(':checked')) {
var ID = $('input[name=getchemist]').parent().parent().siblings('td.chkid').html();
var TO_Area = $('input[name=getchemist]').parent().parent().siblings('td.toarea').html();
}
else {
alert('Please Check');
}
});
In Html:
if (res['status'] == 1) {
var htmlString = '';
$.each(res['data'], function (key, value) {
htmlString += '<tr>';
htmlString += ' <td class="sorting_1"><div class="checkbox-custom checkbox-success"><input type="checkbox" id="checkboxExample3" name="getchemist" class="getchemist" value="' + value.id + '"><label for="checkboxExample3"></label></div></td>';
htmlString += '<td class="chkid">' + value.id + '</td>';
htmlString += '<td>' + value.name + '</td>';
htmlString += '<td>' + value.area + '</td>';
htmlString += '<td class="toarea">' + value.to_area + '</td>';
htmlString += '<td>' + value.address + '</td>';
htmlString += '</tr>';
});
I'm guessing you need values of each td whose checbox are checked. This piece of code should get you started.
As you can see, Code loops through each checkbox which is checked, gets contents inside its corresponding td.
var Result = new Array();
$('.checkbox-custom input[type="checkbox"]:checked').each(function(){
var _this = $(this).closest('tr').find('td');
var id= $(_this).eq(0);
var name = $(_this).eq(1);
................... //Similar way for the others
Result.Push(id,name,....)
});

Can't add data to table with plain JS

function addData() {
var rows = "";
var ID = document.getElementById("id").value;
var Task = document.getElementById("task").value;
rows += "<tr><td>" + ID + "</td><td>" + Task + "</td></tr>";
var tbody = document.querySelector("#table tbody");
var tr = document.createElement("tr");
tr.innerHTML = rows;
tbody.appendChild(tr)
}
<body>
<form onsubmit="" method="POST">
ID:
<input type="text" id="id" required>New task:
<br>
<textarea id="task" required></textarea>
<br>
<input type="submit" value="Add" onclick="addData()">
</form>
<h3>Task Table</h3>
<div id="excell">
<table id="table" cellspacing="0px" cellpadding="25px" text-align="center">
<thead>
<tr>
<td>ID</td>
<td>Task</td>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</body>
I'm learning Javascript and I'm trying to implement a small "ID and Task" table, but somehow it only works when I enter only 1 type of data such as only ID or only task, when I enter 2 data at the same time, nothing happens. I'd be grateful if you tell me what is the problem and how can I fix it. Thank you.
Here's my HTML
<body>
<form onsubmit="" method="POST">
ID:
<input type="text" id="id" required>
New task:<br>
<textarea id="task" required></textarea>
<br>
<input type="submit" value="Add" onclick="addData()">
</form>
<h3>Task Table</h3>
<div id = "excell">
<table id = "table" cellspacing = "0px" cellpadding = "25px" text-align = "center">
<thead>
<tr>
<td>ID</td>
<td>Task</td>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</body>
and here's my JS
function addData() {
var rows = "";
var ID = document.getElementById("id").value;
var Task = document.getElementById("task").value;
rows += "<tr><td>" + ID + "</td><td>" + Task + "</td></tr>";
var tbody = document.querySelector("#table tbody");
var tr = document.createElement("tr");
tr.innerHTML = rows;
tbody.appendChild(tr)
}
Actual problem with your code is, you have used Submit button. Normally when a submit button is hit it post the data to action property of the form tag, which means transfer the page to next; if action property is not given, it give flickering effect and stay with current page and made all components with empty. The same is happen in your code also.
Better Change the code
<input type="Submit" value="Add" onClick="addData();"/>
into
<input type="BUTTON" value="Add" onClick="addData();"/>
and try its worked fine.

Categories