Dynamically change text in table using by clicking a checkbox - javascript

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>

Related

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

Get row index of a table javascript

I know this question has been asked many times, I went through most of the suggestions and none of the solutions seem to be working for me.
I have a table in a modal in which I am allowing the user to make some changes. I then use these values to update the data in the database.
My table rows are created by echoing the HTML code
echo "<tr> ";
echo "<td > $row_counter </td>";
echo "<td style='width:200px' class='left_align' > $lstr_product_name </td>";
echo "<td > $lstr_department_name </td>";
echo "<td > <input type='text' name='unit_cost' class='form-control unit_cost' style='width:50px;' value='$lint_unit_cost' /> <input name='product_id' data-id='$lint_product_id' class='form-control product_id' value='$lint_product_id' type='hidden'/> </td>";
echo "<td > $lint_quantity_counted </td>";
echo "<td > $lint_total_cost </td>";
To update the proper values in the database I need to get the product_id name which I know that I can get by
var x = document.getElementsByName("product_id")[0].value;
However I need to get the correct row index to be able to POST the correct product_id.
I have tried the following:
alert($(this).index());
But this always returns 0. The closest I got to a solution was by using
var rowID = $(this).closest('tr').index();
alert(rowID);
The problem with this is that my editable cell is "unit_cost" which is the 4th cell in the tr. This means that the closest tr is not the one that the row that the cell is in but the one below.
I have then tried
alert( "Row id: " + $("#tbl_store_product_sizes tr").this.rowIndex );
But also no luck. I have ran out of ideas, what is the proper way of doing this?
EDIT
All my javascript code is enclosed in the $(document).ready(function()
I am watching for the change of the unit_cost field using the following code
$(document.body).off( "change", ".unit_cost");
$(document.body).on('change', '.unit_cost', function(event)
{
var rowID = $(this).closest('tr').index();
alert(rowID);
var product_id = document.getElementsByName("product_id")[rowID].value;
alert('The product id is: ' + x);
var unit_cost = document.getElementsByName("unit_cost")[rowID].value;
});
Explanation:-
Since both inputs are in the same <td>, so on change of first-one you have to use .next() to get next input data.
You need to do it like below:-
$(document).on('change', '.unit_cost', function(event) {
var rowID = $(this).closest('tr').index();
alert(rowID);
var product_id = $(this).next('.product_id').val();
alert('The product id is: ' + product_id);
var unit_cost = $(this).val();
});
Working snippet:-
$(document).on('change', '.unit_cost', function(event) {
var rowID = $(this).closest('tr').index();
alert('The corresponding row index is: '+ rowID);
var product_id = $(this).next('.product_id').val();
alert('The product id is: ' + product_id);
var unit_cost = $(this).val();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>1</td>
<td style='width:200px' class='left_align'>2 </td>
<td>3 </td>
<td> <input type='text' name='unit_cost' class='form-control unit_cost' style='width:50px;' value='4' /> <input name='product_id' data-id='$lint_product_id' class='form-control product_id' value='5' type="hidden"/> </td>
<td>6</td>
<td>7</td>
</tr>
<tr>
<td>8</td>
<td style='width:200px' class='left_align'>9 </td>
<td>10 </td>
<td> <input type='text' name='unit_cost' class='form-control unit_cost' style='width:50px;' value='11' /><input name='product_id' data-id='$lint_product_id' class='form-control product_id' value='12' type="hidden"/> </td>
<td>13</td>
<td>14</td>
</tr>
</table>

For loop with array doesn't work with innerHTML

I have a div with the ID="ranking" and I'd like to put there some info of a JavaScript array with a table where every row has tow columns: one for dados[i][25] and other for dados[i][26].
My code is this:
function dadosRanking(dados){
document.getElementById("ranking").innerHTML += '<table class="table"><tr><td valign="middle" class="question" colspan=2><h1>RANKING (+ PONTOS)</h1></td></tr><tr><td>PONTOS</td><td>UTILIZADOR</td></tr>'
for(var i=1;i<6;i++)
{
document.getElementById("ranking").innerHTML += '<tr><td>' + dados[i][25] + '</td><td>' + dados[i][26] + '</td></tr>';
}
document.getElementById("ranking").innerHTML += '</table>';
}
The code I expect was this:
<table class="table">
<tr>
<td valign="middle" class="question" colspan=2>
<h1>RANKING (+ PONTOS)</h1>
</td>
</tr>
<tr>
<td>PONTOS</td>
<td>UTILIZADOR</td>
</tr>
<tr>
<td>
100
</td>
<td>
Username
</td>
</tr>
</table>
However, the HTML code script write is this:
<table class="table">
<tr>
<td valign="middle" class="question" colspan=2>
<h1>RANKING (+ PONTOS)</h1>
</td>
</tr>
<tr>
<td>PONTOS</td>
<td>UTILIZADOR</td>
</tr>
</table>
"100Username"
Everytime you update innerHTML the browser will parse it and render it, to do that it will also try to 'fix' your HTML. This can have unintended consequences. Instead of pushing to innerHTML with a partial table definition, collect the HTML in a separate value and push to innerHTML once.
function dadosRanking(dados){
var s = "";
s += '<table class="table"><tr><td valign="middle" class="question" colspan=2><h1>RANKING (+ PONTOS)</h1></td></tr><tr><td>PONTOS</td><td>UTILIZADOR</td></tr>'
for(var i=1;i<6;i++) {
s += '<tr><td>' + dados[i][25] + '</td><td>' + dados[i][26] + '</td></tr>';
}
s += '</table>';
document.getElementById("ranking").innerHTML += s;
}
After
document.getElementById("ranking").innerHTML += '<table class="table"><tr><td valign="middle" class="question" colspan=2><h1>RANKING (+ PONTOS)</h1></td></tr><tr><td>PONTOS</td><td>UTILIZADOR</td></tr>'
innerHTML becomes:
<table class="table">
<tr><td valign="middle" class="question" colspan=2><h1>RANKING (+ PONTOS)</h1></td></tr>
<tr><td>PONTOS</td><td>UTILIZADOR</td></tr>
</table>
Note that the table has been closed!
After
document.getElementById("ranking").innerHTML += '<tr><td>foo</td><td>bar</td></tr>';
innerHTML becomes
<table>..</table>
foobar
<tr> and <td> are not valid outside of a table context so they're removed.
After
document.getElementById("ranking").innerHTML += '</table>';
innerHTML doesn't change because </table> doesn't do anything, there is no table to close.

Delete function in JavaScript

I trying to delete row from a table but somehow is not working. Could please let me know how can I solve this one ?
here is my html with table and javascript:
<tbody class="items">
<tr>
<td> Data 1 </td>
<td> Data 2 </td>
</tr>
</tbody>
<tbody id="test">
<tr>
<td> </td>
<td> </td>
</tr>
</tbody>
$(".items tr").click(function() {
var value = parseInt($.trim(tableData[1]));
$("#test").append(
"<tr><td><input name='sm_invnumber[]' value='" +
$.trim(tableData[0]) +
"' style='width: 170px;' readonly ></td><td><input name='sm_amount[]' value='" +
$.trim(tableData[1]) +
"' style='width: 170px; text-align: right;' readonly ></td><td><span onclick='deleteRow(value, this)'> x </span> </td></tr>");
});
function deleteRow(value, row) {
var i = row.parentNode.parentNode.rowIndex;
document.getElementById('#test').deleteRow(i);
}
Here is the instruction that I am working with: Picking data by clicking on table (class= items) and place to them into table (id=test). there is a function with 'X'. I want to delete this row.
Helps are highly appreciated.
You seem to making your life very difficult. Why not simply add a class to the cell that has the cross and use jQuery to remove its containing row. For example:
<table>
<tbody id="test">
<tr><td>Data 1</td><td class="delete">x</td></tr>
<tr><td>Data 2</td><td class="delete">x</td></tr>
<tr><td>Data 3</td><td class="delete">x</td></tr>
</tbody>
</table>
$('.delete').click(function () {
$(this).parent().remove();
});
Fiddle
try this
function deleteRow(value, span)
{
$(span).closest("tr").remove();
}
or
function deleteRow(value, span)
{
var i=row.parentNode.parentNode.rowIndex;
$(document.getElementById('test')).children(":eq("+i+")").remove();
}
There are few poblems, try
jQuery(function () {
var tableData = [1, 'test'];
$(".items tr").click(function () {
var value = parseInt($.trim(tableData[1]));
$("#test").append(
"<tr><td><input name='sm_invnumber[]' value='" + $.trim(tableData[0]) + "' style='width: 170px;' readonly ></td><td><input name='sm_amount[]' value='" + $.trim(tableData[1]) + "' style='width: 170px; text-align: right;' readonly ></td><td><span onclick='deleteRow(\"" + value + "\",this)'> x </span> </td></tr>");
});
})
function deleteRow(value, row) {
$(row).closest('tr').remove();
}
Demo: Fiddle, another version

Add, edit and delete function to my javascript

I'm looking to add edit and delete functionality to the following JavaScript and I'm not sure where exactly to start.
This functions just fine as a input add but It needs to be editable and deletable. Is Javascript the way to go here?
HTML
<table width="600px" class="setpoint-form-table">
<tr>
<td colspan="5">
<p style="font-size:16px; float:left;">First Name / Last Name Table Post and Edit</p>
</td>
</tr>
<tr>
<td colspan="5" height="20px"></td>
</tr>
<tr>
<input type="text" id="RowPlaceholder2" style="visibility:hidden;" />
<td width="100px" style="font-size:14px">First Name</td>
<td><input type="text" id="fName" class="setpoint-textbox" /></td>
<td width="100px" style="font-size:14px;">Last Name</td>
<td><input type="text" id="lName" class="setpoint-textbox" /></td>
<td><button type="button" id="edit">Edit</button></td>
</tr>
<tr>
<td colspan="5" height="20px"></td>
</tr>
<tr>
<td colspan="5"><button type="button" onclick="HvacStandards()">Submit</button></td>
</tr>
<tr>
<td colspan="5">
<br />
<br />
<table width="600px" id="testingWithEdit">
<tr>
<td style="background-color:#fff; color:#00468C; border-bottom:1px solid #000; border-right:1px solid #000;">First Name</td>
<td style="background-color:#fff; color:#00468C; border-bottom:1px solid #000;">Last Name</td>
</tr>
</table>
</td>
</tr>
</table>
JavaScript
function HvacStandards() {
var rowID = document.getElementById("RowPlaceholder2").value;
var firstName = document.getElementById("fName").value;
var lastName = document.getElementById("lName").value;
var sHtml = "<tr>" +
"<td id=\"firstName" + rowID + "\">" + firstName + "</td>" +
"<td id=\"lastName" + rowID + "\">" + lastName + "</td>" +
"</tr>";
$("#testingWithEdit").append(sHtml);
rowID++;
document.getElementById("RowPlaceholder2").value = rowID;
document.getElementById("fName").value = "";
document.getElementById("lName").value = "";
}
Here's just one of the many ways to do this:
In this fiddle, I simply added an extra column to sHTML containing edit and delete buttons that call editRow() and deleteRow() respectively, both passing the parameter of the rowID.
I then defined two new global variables, newRow and currentRow. I then modified HvacStandards use newRow as the RowID. Additionally, I modified it to switch to saveEdits if currentRow is not -1, so that hitting the submit button saves the edits instead of just creating a new row.
Then I created the the editRow function that fills the textboxes with the html contained within firstName+rowID and lastName+rowID, and then set currentRow to the rowID.
The saveEdits function then modifies the html of the table rows to the new values from the inputs, clears the inputs, and then resets currentRow to -1 so hitting submit will add a new row next time.
Finally, the deleteRow function simply removes the row from the dom. (I added an id to the tr in sHTML so that the row as a whole can be identified).
Let me know if this all makes sense and does what you need it to do :)

Categories