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

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);
});

Related

Calculate the row date depending on previous row in the table

I have this dynamic table. Add more button append a new row. Row consists of number or days and date field. Means how many days added results in date.
Now in the second row, if I add a number of days; it must check the previous previous row date or number and result the date. But rowSelected.prev('tr')[0] gives me no value.
Can anybody please help me.
$(function() {
$("#add-more").click(function() {
$("#main-table").each(function() {
let tds = '<tr>';
jQuery.each($('tr:last td', this), function() {
tds += '<td>' + $(this).html() + '</td>';
});
tds += '</tr>';
if ($('tbody', this).length > 0) {
$('tbody', this).append(tds);
} else {
$(this).append(tds);
}
});
});
$(document).on('change', '.total-days', function(e) {
let rowSelected = $(this).closest('tr');
const someDate = new Date();
someDate.setDate(someDate.getDate() + parseInt($(this).val()));
const newDate = someDate.toISOString().substr(0, 10);
rowSelected.find('.expected-delivery-date').val(newDate);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div class="col-sm-6 right">
<a class="inline btn btn-primary" id="add-more">Add More</a>
</div>
<table class="table table-bordered" id="main-table" border="1">
<thead>
<tr>
<th>No.</th>
<th>From</td>
<th>Expected Delivery Date</td>
</tr>
</thead>
<tbody id="rows">
<tr>
<td><input class="form-control" type="text" name="deliverableNumber[]" /></td>
<td><input class="form-control total-days" type="number" value="1" name="deliverableNumberOfDays[]" /></td>
<td>
<input class="form-control expected-delivery-date" type="date" name="deliverableExpectedDeliveryDate[]" />
</td>
<td><i class="fa-2x fa fa-trash" onclick="SomeDeleteRowFunction(this)" title="Remove row"></i></td>
</tr>
</tbody>
</table>

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;">

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

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>

Dynamically change text in table using by clicking a checkbox

I have a data in JSON format and I convert it to a HTML table. Now I want to
change the text from False to True if I check the checkbox. How can I do that?
Here is the code for creating the HTML table:
$.each(result, function (index, value) {
var Data = "<tr>" +
"<td class='' id='stdID' >" + value.StudentID + "</td>" +
"<td class='' id='stdRol'>" + value.RollNo + "</td>" +
"<td class='' id='stdName'>" + value.FirstName + "</td>" +
"<td class='cbx' value='1'><input type='checkbox' id='cc"+index+"'><span id='checkbox-value'> False</span></td>" +
"</tr>";
SetData.append(Data);
This is the result of this: output
To achieve what you require you need to use a delegated event handler, as you dynamically append the rows after the page has loaded, to hook to the change event of the checkboxes. Then you can set the text of the sibling span element based on the checked property. Something like this:
$('table').on('change', ':checkbox', function() {
$(this).next('span').text(this.checked);
});
span.checkbox-value { text-transform: capitalize; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td class="stdID">value.StudentID</td>
<td class="stdRol">value.RollNo</td>
<td class="stdName">value.FirstName</td>
<td class="cbx" value="1">
<input type="checkbox" id="cc1">
<span class="checkbox-value">False</span>
</td>
</tr>
<tr>
<td class="stdID">value.StudentID</td>
<td class="stdRol">value.RollNo</td>
<td class="stdName">value.FirstName</td>
<td class="cbx" value="1">
<input type="checkbox" id="cc2">
<span class="checkbox-value">False</span>
</td>
</tr>
</table>
You should note that your loop is creating multiple elements which have the same id, which is invalid HTML. In the example above I've changed them to classes instead.
Another way around to achieve your desired output
$(document).on('change', '.changeStatus', function() {
var row = $(this).closest('tr');
if($(this). prop("checked") == true){
row.find('.changeValue').html('True');
} else {
row.find('.changeValue').html('False');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<td>Id</td>
<td>Roll_no</td>
<td><input type="checkbox" class="changeStatus"></td>
<td class="changeValue">False</td>
</tr>
<tr>
<td>Id</td>
<td>Roll_no</td>
<td><input type="checkbox" class="changeStatus"></td>
<td class="changeValue">False</td>
</tr>
<tr>
<td>Id</td>
<td>Roll_no</td>
<td><input type="checkbox" class="changeStatus"></td>
<td class="changeValue">False</td>
</tr>
</tbody>
</table>

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,....)
});

Categories