Hiding a button in a certain display - javascript

I have the following data table where it has 2 control buttons, edit and save. The issue I am having is hiding the save button from the first preview.
(The output I am trying to achieve is on the first page it should only display Edit and when a user clicks on Edit it should display save.)
please see the snippet for further explanation.
function edit_row(id)
{
var name=document.getElementById("name_val"+id).innerHTML;
var age=document.getElementById("age_val"+id).innerHTML;
document.getElementById("name_val"+id).innerHTML="<input type='text' id='name_text"+id+"' value='"+name+"'>";
document.getElementById("age_val"+id).innerHTML="<input type='text' id='age_text"+id+"' value='"+age+"'>";
document.getElementById("edit_button"+id).style.display="none";
document.getElementById("save_button"+id).style.display="block";
}
function save_row(id)
{
var name=document.getElementById("name_text"+id).value;
var age=document.getElementById("age_text"+id).value;
$.ajax
({
type:'post',
url:'modify_records.php',
data:{
edit_row:'edit_row',
row_id:id,
name_val:name,
age_val:age
},
success:function(response) {
if(response=="success")
{
document.getElementById("name_val"+id).innerHTML=name;
document.getElementById("age_val"+id).innerHTML=age;
document.getElementById("edit_button"+id).style.display="block";
document.getElementById("save_button"+id).style.display="none";
}
}
});
}
function delete_row(id)
{
$.ajax
({
type:'post',
url:'modify_records.php',
data:{
delete_row:'delete_row',
row_id:id,
},
success:function(response) {
if(response=="success")
{
var row=document.getElementById("row"+id);
row.parentNode.removeChild(row);
}
}
});
}
function insert_row()
{
var name=document.getElementById("new_name").value;
var age=document.getElementById("new_age").value;
$.ajax
({
type:'post',
url:'modify_records.php',
data:{
insert_row:'insert_row',
name_val:name,
age_val:age
},
success:function(response) {
if(response!="")
{
var id=response;
var table=document.getElementById("user_table");
var table_len=(table.rows.length)-1;
var row = table.insertRow(table_len).outerHTML="<tr id='row"+id+"'><td id='name_val"+id+"'>"+name+"</td><td id='age_val"+id+"'>"+age+"</td><td><input type='button' class='edit_button' id='edit_button"+id+"' value='edit' onclick='edit_row("+id+");'/><input type='button' class='save_button' id='save_button"+id+"' value='save' onclick='save_row("+id+");'/><input type='button' class='delete_button' id='delete_button"+id+"' value='delete' onclick='delete_row("+id+");'/></td></tr>";
document.getElementById("new_name").value="";
document.getElementById("new_age").value="";
}
}
});
}
<table align="center" cellpadding="10" border="1" id="user_table">
<tr>
<th>NAME</th>
<th>AGE</th>
<th></th>
</tr>
<tr id="">
<td id="name_val">Test Name</td>
<td id="age_val">Test Age</td>
<td>
<input type='button' class="edit_button" id="edit_button" value="edit" onclick="edit_row('');">
<input type='button' class="save_button" id="save_button" value="save" onclick="save_row('');">
</tr>
<?php
}
?>
</table>

Just add this css.
.save_button{
display: none;
}
or go for inline css style="display:none" for first display.
function edit_row(id)
{
var name=document.getElementById("name_val"+id).innerHTML;
var age=document.getElementById("age_val"+id).innerHTML;
document.getElementById("name_val"+id).innerHTML="<input type='text' id='name_text"+id+"' value='"+name+"'>";
document.getElementById("age_val"+id).innerHTML="<input type='text' id='age_text"+id+"' value='"+age+"'>";
document.getElementById("edit_button"+id).style.display="none";
document.getElementById("save_button"+id).style.display="block";
}
function save_row(id)
{
var name=document.getElementById("name_text"+id).value;
var age=document.getElementById("age_text"+id).value;
$.ajax
({
type:'post',
url:'modify_records.php',
data:{
edit_row:'edit_row',
row_id:id,
name_val:name,
age_val:age
},
success:function(response) {
if(response=="success")
{
document.getElementById("name_val"+id).innerHTML=name;
document.getElementById("age_val"+id).innerHTML=age;
document.getElementById("edit_button"+id).style.display="block";
document.getElementById("save_button"+id).style.display="none";
}
}
});
}
function delete_row(id)
{
$.ajax
({
type:'post',
url:'modify_records.php',
data:{
delete_row:'delete_row',
row_id:id,
},
success:function(response) {
if(response=="success")
{
var row=document.getElementById("row"+id);
row.parentNode.removeChild(row);
}
}
});
}
function insert_row()
{
var name=document.getElementById("new_name").value;
var age=document.getElementById("new_age").value;
$.ajax
({
type:'post',
url:'modify_records.php',
data:{
insert_row:'insert_row',
name_val:name,
age_val:age
},
success:function(response) {
if(response!="")
{
var id=response;
var table=document.getElementById("user_table");
var table_len=(table.rows.length)-1;
var row = table.insertRow(table_len).outerHTML="<tr id='row"+id+"'><td id='name_val"+id+"'>"+name+"</td><td id='age_val"+id+"'>"+age+"</td><td><input type='button' class='edit_button' id='edit_button"+id+"' value='edit' onclick='edit_row("+id+");'/><input type='button' class='save_button' id='save_button"+id+"' value='save' onclick='save_row("+id+");'/><input type='button' class='delete_button' id='delete_button"+id+"' value='delete' onclick='delete_row("+id+");'/></td></tr>";
document.getElementById("new_name").value="";
document.getElementById("new_age").value="";
}
}
});
}
.save_button{
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table align="center" cellpadding="10" border="1" id="user_table">
<tr>
<th>NAME</th>
<th>AGE</th>
<th></th>
</tr>
<tr id="">
<td id="name_val">Test Name</td>
<td id="age_val">Test Age</td>
<td>
<input type='button' class="edit_button" id="edit_button" value="edit" onclick="edit_row('');">
<input type='button' class="save_button" id="save_button" value="save" onclick="save_row('');">
</tr>
<?php
}
?>
</table>

Initially set the display:none for the Save button in your HTML Code like this following code,
<input type='button' class="edit_button" id="edit_button" value="edit"
onclick="edit_row('');" style="display:block;">
<input type='button' class="save_button" id="save_button" value="save"
onclick="save_row('');" style="display:none;">

Related

Ajax send array of data to backend

I have table where I loop dynamic data and each of those dynamic items has input fields then I send those input fields along with dynamic items id to back-end.
Issue
Issue is that my fields in ajax giving me strange data as array.
Code
$(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('.newservicesSave').on('click', function(e) {
e.preventDefault();
e.stopPropagation();
var idmess = $(this).data("id");
// this array data are wrong
var newservices = [];
$(".newservices").each(function() {
newservices.push($(this).val());
});
console.log('newservices: ', newservices);
$.ajax({
url: '{{ url('
panel / addnewservices ') }}/' + encodeURI(idmess),
type: 'POST',
dataType: "JSON",
data: {
"id": idmess,
"newservices": newservices,
"_method": 'POST',
"_token": "{{ csrf_token() }}",
},
success: function(data) {
$('#servicesTable').empty();
$.each(data.data, function(key, value) {
$("#servicesTable").append('<tr><td>' + value['name'] + '</td><td><textarea name="' + services['key']['description'] + '" class="form-control" name="description"></textarea><input type="hidden" name="' + services['key']['service_id'] + '"/></td><td><input type="text" class="form-control" placeholder="Harga" name="' + services['key']['price'] + '"/></td><td><input class="form-checkbox" type="checkbox" name="' + services['key']['active'] + '" /></td></tr>');
});
}
});
});
});
<table class="table table-bordered table-striped table-hover">
<thead>
<tr>
<th>Service</th>
<th>Description</th>
<th>Harga</th>
<th>Active</th>
</tr>
</thead>
<tbody>
#foreach($services as $index => $service)
<tr>
<td>{{$service->name}}</td>
<td>
<textarea name="newservices[{{$index}}][description]" class="newservices form-control" name="description"></textarea>
<input type="hidden" class="newservices" name="newservices[{{$index}}][service_id]" />
</td>
<td>
<input type="text" class="newservices form-control" placeholder="Harga" name="newservices[{{$index}}][price]" />
</td>
<td><input class="newservices form-checkbox" type="checkbox" name="newservices[{{$index}}][active]" /></td>
</tr>
#endforeach
</tbody>
</table>
<button type="button" data-id="{{$laundry->id}}" class="newservicesSave btn btn-primary">Save changes</button>
Result
Expected data from ajax
Data should come to backend as follow structure
newservices [
0 [
active => 0,
service_id => '123456',
description => 'abc',
price => '1000'
],
1 [...],
2 [...],
// etc.
]
Any idea?
To get the structure you want you will need to loop over rows and create an object for each row
Try something like :
var newservices = $('#myTable tbody tr').map(function(){
var $row = $(this);
return {
description: $row.find('.newservices[name*="description"]').val(),
service_id : $row.find('.newservices[name*="service_id"]').val(),
// ... same for other properties
}
}).get();

Form inside while loop is sending only the 1st row data via ajax

I have a form inside a while loop which I want to use to update the database using ajax. The problem is that when I am using ID only the 1st data or 1st row data of the form is sent no matter which button I click. When I change the IDs to CLASSES the console shows undefined.
Error in Console when using classes:
Object { credits: undefined, price: undefined, packId: undefined, type: "savePackage" }
HTML Form:
<div class="content">
<div class="content table-responsive table-full-width">
<table class="table table-hover table-striped">
<tr>
<th>Credits</th>
<th>Price</th>
<th>Action</th>
</tr>
<?php while($pack = $package->fetch()){ extract($pack); ?>
<tr>
<form method="post" action="">
<input type="hidden" value="<?php echo $cp_id; ?>" class="packId">
<td><input type="text" class="form-control" class="editCredits" value="<?php echo $cp_credits; ?>"></td>
<td><input type="text" class="form-control" class="editPrice" value="<?php echo $cp_price; ?>"></td>
<td>
<input type="submit" value="Save" class="btn btn-fill btn-info savePackage">
<input type="submit" value="Delete" class="btn btn-fill btn-danger deletePackage">
</td>
</form>
</tr>
<?php } ?>
</table>
</div>
</div>
AJAX Code
$(document).ready(function() {
$(".savePackage").click(function() {
var dataString = {
credits: $(this).closest('form').find('.editCredits').val(),
price: $(this).closest('form').find('.editPrice').val(),
packId: $(this).closest('form').find('.packId').val(),
type: 'savePackage'
};
console.log(dataString);
var $submit = $(this).parent().find('.savePackage');
$.confirm({
title: 'Confirm!',
content: 'Are you sure you want to add this package?',
buttons: {
confirm: function () {
$.ajax({
type: "POST",
//dataType : "json",
url: "ptc-settings-process.php",
data: dataString,
cache: true,
beforeSend: function(){
$submit.val("Please wait...");
},
success: function(html){
$.alert(html);
$submit.val("Save");
}
});
},
cancel: function(){}
}
});
return false;
});
});
I have used $(this).closest('form').find('.editCredits').val() method here but there are multiple other forms on the same page too. Therefore, maybe using form element in $(this).closest('form') could be causing a problem.
Inside your $(".savePackage").click, the form you are looking for with $(this).closest('form') is not found.
I think that is because you have your form inside the table structure after the <tr>.
What you could do is move your form to before the <table> definition:
<form method="post" action="">
<table class="table table-hover table-striped">
You also have a duplicate class definition class="form-control" class="editCredits" in your <input>.
You could update that to class="form-control editCredits"
Instead of using multiple forms, and find the form you could find the closest <tr> and then find the <td> with the input and the class.
Your code might then look like:
$(document).ready(function() {
$(".savePackage").click(function() {
var dataString = {
credits: $(this).closest('tr').find('td input.editCredits').val(),
price: $(this).closest('tr').find('td input.editPrice').val(),
packId: $(this).closest('tr').find('.packId').val(),
type: 'savePackage'
};
console.log(dataString);
var $submit = $(this).parent().find('.savePackage');
$.confirm({
title: 'Confirm!',
content: 'Are you sure you want to add this package?',
buttons: {
confirm: function() {
$.ajax({
type: "POST",
//dataType : "json",
url: "ptc-settings-process.php",
data: dataString,
cache: true,
beforeSend: function() {
$submit.val("Please wait...");
},
success: function(html) {
$.alert(html);
$submit.val("Save");
}
});
},
cancel: function() {}
}
});
return false;
});
});
<div class="content">
<div class="content table-responsive table-full-width">
<form method="post" action="">
<table class="table table-hover table-striped">
<tr>
<th>Credits</th>
<th>Price</th>
<th>Action</th>
</tr>
<?php while($pack = $package->fetch()){ extract($pack); ?>
<tr>
<input type="hidden" value="<?php echo $cp_id; ?>" class="packId">
<td><input type="text" class="form-control editCredits" value="<?php echo $cp_credits; ?>">
</td>
<td><input type="text" class="form-control editPrice" value="<?php echo $cp_price; ?>"></td>
<td>
<input type="submit" value="Save" class="btn btn-fill btn-info savePackage">
<input type="submit" value="Delete" class="btn btn-fill btn-danger deletePackage">
</td>
</tr>
<?php } ?>
</table>
</form>
</div>
</div>

ajax, php how to save correctly data

I tried to send information via ajax about user_question and language input fields, but how to write correctly this element inside ajax javascript to save the table element value in database.
thank you.
the script element.
<table id="myTable" class="table table-sm table-hover order-list">
<thead>
<tr>
<td>User Question</td>
<td>Language</td>
</tr>
</thead>
<tbody>
<tr>
<td class="col-md-9">' . HTML::inputField('user_question', null, 'placeholder="Write a short answer"'). '</td>
<td class="col-md-2">' . HTML::inputField('language', null, 'placeholder="Language"') . '</td>
<td class="col-sm-1"><a id="delete_row" class="deleteRow"></a></td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="5">
<input type="button" class="btn btn-lg btn-block " id="addrow" value="Add Row" />
</td>
</tr>
<tr></tr>
</tfoot>
</table>
<script>
$(document).ready(function () {
var counter = 0;
$("#addrow").on("click", function () {
var newRow = $("<tr>");
var cols = "";
cols += '<td><input type="text" class="form-control" name="user_question' + counter + '"/></td>';
cols += '<td><input type="text" class="form-control" name="language' + 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++;
// element pb
// var data = $("#new_product").serialize(); // form id or table id ?
var dataString = 'user_question='+user_question+'language='+language;
$.ajax({
type: 'POST',
url: '{$ajax_url}',
data : dataString,
success: function(data) {
alert(data);
$("p").text(data);
}
});
$("table.order-list").on("click", ".ibtnDel", function (event) {
$(this).closest("tr").remove();
counter -= 1
});
});
</script>
Use like this to get php variables value inside javascript in .php page
url: "<?php echo $ajax_url; ?>",
Also use & and symbol to add two or more param in your dataString

Why is .getElementById("name_val"+id).innerHTML is null?

I am trying to differentiate each id with their corresponding id from database. For Eg: Name_val19. The line var name=document.getElementById("name_val"+id).innerHTML; is returning null value. The value is being stored in database also
function edit_row(id)
{
var name=document.getElementById("name_val"+id).innerHTML;
var age=document.getElementById("age_val"+id).innerHTML;
document.getElementById("name_val"+id).innerHTML="<input type='text' id='name_text"+id+"' value='"+name+"'>";
document.getElementById("age_val"+id).innerHTML="<input type='text' id='age_text"+id+"' value='"+age+"'>";
document.getElementById("edit_button"+id).style.display="none";
document.getElementById("save_button"+id).style.display="block";
}
function save_row(id)
{
var name=document.getElementById("name_val"+id).value;
var age=document.getElementById("age_val"+id).value;
$.ajax
({
type:'post',
url:'modify_records.php',
data:{
edit_row:'edit_row',
row_id:id,
name_val:name,
age_val:age
},
success:function(response) {
if(response=="success")
{
document.getElementById("name_val"+id).innerHTML=name;
document.getElementById("age_val"+id).innerHTML=age;
document.getElementById("edit_button"+id).style.display="block";
document.getElementById("save_button"+id).style.display="none";
}
}
});
}
function delete_row(id)
{
$.ajax
({
type:'post',
url:'modify_records.php',
data:{
delete_row:'delete_row',
row_id:id,
},
success:function(response) {
if(response=="success")
{
var row=document.getElementById("row"+id);
row.parentNode.removeChild(row);
}
}
});
}
function insert_row()
{
var name=document.getElementById("new_name").value;
var age=document.getElementById("new_age").value;
$.ajax
({
type:'post',
url:'modify_records.php',
data:{
insert_row:'insert_row',
name_val:name,
age_val:age
},
success:function(response) {
if(response!="")
{
var id=response;
var table=document.getElementById("user_table");
var table_len=(table.rows.length)-1;
var row = table.insertRow(table_len).outerHTML="<tr id='row"+id+"'><td id='name_val"+id+"'>"+name+"</td><td id='age_val"+id+"'>"+age+"</td><td><input type='button' class='edit_button' id='edit_button"+id+"' value='Edit' onclick='edit_row("+id+");'/><input type='button' class='save_button' id='save_button"+id+"' value='Save' onclick='save_row("+id+");'/><input type='button' class='delete_button' id='delete_button"+id+"' value='Delete' onclick='delete_row("+id+");'/></td></tr>";
document.getElementById("new_name").value="";
document.getElementById("new_age").value="";
}
}
});
}
$("#insert").submit(function() {
var name= $("#new_name").val();
var password= $("#new_age").val();
$.ajax({
type: "POST",
url: "connect.php",
data: "name=" + name+ "&password=" + password,
success: function(data) {
alert("sucess");
}
});
});
PHP Code:
<html>
<head>
</head>
<body>
<div id="wrapper">
<table align="center" cellpadding="10" border="1" id="user_table">
<tr>
<th>NAME</th>
<th>AGE</th>
<th></th>
</tr>
<?php
include "connect.php";
$select=mysqli_query($connection,"SELECT * FROM user_detail");
if($select!=NULL){
while ($row=mysqli_fetch_array($select,MYSQLI_BOTH))
{
?>
<tr id="row<?php echo $row['id'];?>">
<td id="name_val<?php echo row['id'];?>"><?php echo $row['name'];?></td>
<td id="age_val<?php echo $row['id'];?>"><?php echo $row['age'];?></td>
<td>
<button class="edit_button" id="edit_button<?php echo $row['id'];?>" onclick="edit_row('<?php echo $row['id'];?>');">Edit</button>
<button class="save_button" id="save_button<?php echo $row['id'];?>" onclick="save_row('<?php echo $row['id'];?>');">Save</button>
<button class="delete_button" id="delete_button<?php echo $row['id'];?>" onclick="delete_row('<?php echo $row['id'];?>');">Delete</button>
</td>
</tr>
<?php
}
}
?>
<tr id="new_row"><form id="insert" onclick="insert_db()">
<td><input type="text" id="new_name"></td>
<td><input type="text" id="new_age"></td>
<td><button type="button" value="Insert Row" onclick="insert_row()">Insert</button></td>
</form></tr>
</table>
</div>
</body>
<script type="text/javascript" src="./js/jquery-3.2.0.js"></script>
<script type="text/javascript" src="./js/modify_records.js"></script>
</html>
looks like a few things, first i recommend getting the element by class since your id is complicated, try using getElementByClass("edit_button") to get <button class="edit_button" id="...">
getElementById() does exactly that, you are trying to get a dom (html) element by its id="" attribute, into the js Scope so you can do something with it. it should be getElementById("IDofElement")
getElementById("row") gets <p id="row"> </p>
but it looks like you set
var id=response; which makes your
getElementById("IDofElement"+"ENTIRE AJAX RESPONSE") call throw an error because there is no dom element with an id of e.g.
<div id="rowENTIRE-AJAX-RESPONSE"></div>
You're killing yourself with all these IDs. Use HTML5 data-attribute to store your record's ID once per row.
<tr data-id="<?php echo $row['id'] ?>">
<!-- added class names to cells bc we'll be using them later -->
<td class="name"><?php echo $row['name'] ?></td>
<td class="age"><?php echo $row['age'] ?></td>
<td>
<button type="button" class="edit_button">Edit</button>
<button type="button" class="save_button">Save</button>
<button type="button" class="delete_button">Delete</button>
</td>
</tr>
Utilize jQuery to its full potential to find elements (e.g. .find() and .closest()) and attach event handlers. document.getElementById and onclick attributes are so passé when it comes to jQuery.
Your code can be cleaner:
$('.edit_button').click(function () {
var tr = $(this).closest('tr'),
tdName = tr.find('td.name'),
tdAge = tr.find('td.age');
var id = tr.data('id'),
name = tdName.text(),
age = tdAge.text();
tdName.html('<input type="text" name="name" value="' + name + '">');
tdAge.html('<input type="text" name="age" value="' + age + '">');
tr.find('.edit_button').hide();
tr.find('.save_button').show();
});
$('.save_button').click(function () {
var tr = $(this).closest('tr'),
tdName = tr.find('td.name'),
tdAge = tr.find('td.age');
var id = tr.data('id'),
name = tdName.find('input').val(),
age = tdAge.find('input').val();
// shorthand method for $.ajax POST
$.post('modify_records.php', {
edit_row: 'edit_row',
row_id: id,
name_val: name,
age_val: age
}, function (response) {
if (response == "success") {
tdName.html(name);
tdAge.html(age);
tr.find('.edit_button').show();
tr.find('.save_button').hide();
}
});
});
$('.delete_button').click(function () {
var tr = $(this).closest('tr')
var id = tr.data('id');
$.post('modify_records.php', { delete_row: 'delete_row', row_id: id }, function (response) {
if (response == "success") {
tr.remove();
}
});
});
Quick demo
$('.edit_button').click(function() {
var tr = $(this).closest('tr'),
tdName = tr.find('td.name'),
tdAge = tr.find('td.age');
var id = tr.data('id'),
name = tdName.text(),
age = tdAge.text();
tdName.html('<input type="text" name="name" value="' + name + '">');
tdAge.html('<input type="text" name="age" value="' + age + '">');
tr.find('.edit_button').hide();
tr.find('.save_button').show();
});
$('.save_button').click(function() {
var tr = $(this).closest('tr'),
tdName = tr.find('td.name'),
tdAge = tr.find('td.age');
var id = tr.data('id'),
name = tdName.find('input').val(),
age = tdAge.find('input').val();
console.log('saving', id, name, age)
$.post('modify_records.php', {
edit_row: 'edit_row',
row_id: id,
name_val: name,
age_val: age
}, function(response) {
if (response == "success") {
tdName.html(name);
tdAge.html(age);
tr.find('.edit_button').show();
tr.find('.save_button').hide();
}
});
});
$('.delete_button').click(function() {
var tr = $(this).closest('tr')
var id = tr.data('id');
console.log('deleting', id)
$.post('modify_records.php', {
delete_row: 'delete_row',
row_id: id
}, function(response) {
if (response == "success") {
tr.remove();
}
});
});
.save_button {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr data-id="1">
<td class="name">Bill</td>
<td class="age">21</td>
<td>
<button type="button" class="edit_button">Edit</button>
<button type="button" class="save_button">Save</button>
<button type="button" class="delete_button">Delete</button>
</td>
</tr>
<tr data-id="2">
<td class="name">Sarah</td>
<td class="age">22</td>
<td>
<button type="button" class="edit_button">Edit</button>
<button type="button" class="save_button">Save</button>
<button type="button" class="delete_button">Delete</button>
</td>
</tr>
<tr data-id="3">
<td class="name">Jean</td>
<td class="age">34</td>
<td>
<button type="button" class="edit_button">Edit</button>
<button type="button" class="save_button">Save</button>
<button type="button" class="delete_button">Delete</button>
</td>
</tr>
</table>

Showing checked checkbox rows first in the table

I have written a code which is populating a html table using ajax call using the following code -
$.ajax({
type: "POST",
url: "my_url",
data: JSON.stringify(result),
async: true,
dataType: "json",
contentType: "application/json; charset= Shift-JIS",
success: function (response) {
glResp = response;
populateTable(glResp);
},
error: function (error) {
console.log(error);
//alert("Error!!");
}
});
The data is being correctly shown on the table with a checkbox in front of each row. Now I want to show the rows which have checked checkboxes in the table first and rest of the rows after that. I have written the following code but it doesn`t seem to work. Anyone can help?
function populateTable(finalObject) {
var obj = finalObject;
var headers1 = ['Name', 'City', 'Job', 'Salary'];
var table = $("<table id='my-table' />");
var columns = headers1;
columns.unshift('');
var columnCount = columns.length;
var row = $(table[0].insertRow(-1));
for (var i = 0; i < columnCount; i++) {
if (i == 0) {
var headerCell = $("<th><input type='button' id='sort'></th>");
row.append(headerCell);
}
else {
var headerCell = $("<th/>");
headerCell.html([columns[i]]);
row.append(headerCell);
}
}
$.each(obj, function (i, obj) {
$row = '<tr><td><input type="checkbox"></td><td>' + obj.Name + '</td><td>' + obj.City + '</td><td>' + obj.Job + '</td><td>' + obj.Salary + '</td></tr>';
table.append(row);
});
var dvTable = $("#dvCSV");
dvTable.html("");
dvTable.append(table);
}
$(function () {
$('#sort').on('click', function () {
var newTable = $('<table class="table"></table>');
$('.my-table').find('tr').each(function ($index, $value) {
if ($(this).find('input[type=checkbox]').is(':checked')) {
newTable.prepend($(this));
} else {
newTable.append($(this));
}
});
$('.table').replaceWith(newTable);
});
});
You can do it like following. Loop through all tr as you are doing and append the tr which have unchecked checkbox at the last of table.
$('#dvCSV').on('click', '#sort', function () {
$('#my-table').find('tr:not(:first)').each(function () {
if (!$(this).find(':checkbox').is(':checked'))
$('#my-table').append(this);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="my-table">
<tr>
<th>
X
</th>
<th>Row Name</th>
</tr>
<tr>
<td>
<input type="checkbox" />
</td>
<td>Row 1</td>
</tr>
<tr>
<td>
<input type="checkbox" />
</td>
<td>Row 2</td>
</tr>
<tr>
<td>
<input type="checkbox" />
</td>
<td>Row 3</td>
</tr>
<tr>
<td>
<input type="checkbox" />
</td>
<td>Row 4</td>
</tr>
<tr>
<td>
<input type="checkbox" />
</td>
<td>Row 5</td>
</tr>
</table>
<div id="dvCSV">
<button id="sort">Sort</button>
</div>

Categories

Resources