I have created a website mainly using HTML, CSS, PHP and MYSQL and I added a select dropdown with roles for to users to choose from. I need it to be on every row of users in the table. I have successfully gotten tabledit working on the site, but I am not sure how to append this dropdown to the Roles column.
This is how the HTML is set up
<body>
<div class="panel panel-default">
<!-- <div class="panel-heading">Sample Data</div>-->
<div class="panel-body">
<div class="table-responsive">
<table id="sample_data" class="table table-bordered table-striped">
<thead>
<tr>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Approval</th>
<th>Roles</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
<!--SELECT DROPDOWN LIST-->
<select id="test">
<?php
for ($a = 1; $a <= $count ; $a++){
?>
<option value="1"><?php echo($roles[($a-1)]);?></option>
<?php
}
?>
</select>
<!--//////////////-->
</body>
<script>
$(document).ready(function(){
var dataTable = $('#sample_data').DataTable({
"processing" : true,
"serverSide" : true,
"order" : [],
"ajax" : {
url:"FetchUserTable.php",
type:"POST"
}
});
$('#sample_data').on('draw.dt', function(){
$('#sample_data').Tabledit({
url:'ActionUserTable.php',
dataType:'json',
columns:{
identifier : [0, 'user_id'],
editable:[
[1, 'first_name'],
[2, 'last_name'],
[3, 'email'],
[4, 'admin_approved', '{"1":"Approved","2":"Disapproved"}']
// [5, 'role_id']
]
},
restoreButton:false,
onSuccess:function(data, textStatus, jqXHR)
{
if(data.action == 'delete')
{
$('#' + data.id).remove();
$('#sample_data').DataTable().ajax.reload();
}
}
});
});
});
You can use the render option on the column definitions to render what ever you want. In the render function you have access to the row and the entire data object.
$(function() {
let $tbl = $('#sample_data'), $select = $('#select-box')
let data = [
[
"Tiger Nixon",
"System Architect",
"Edinburgh",
"5421",
"2011/04/25",
"$3,120"
],
[
"Garrett Winters",
"Director",
"Edinburgh",
"8422",
"2011/07/25",
"$5,300"
]
]
$tbl.DataTable({
data: data,
columns: [
null, null, null, null, {
render: function(data, type, row, meta) {
return $select.html() + `Use this to select "${data}"`
}
},
{
render: function(data, type, row, meta) {
return $select.html() + `Use this to select "${data}"`
}
},
]
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/dt-1.10.22/datatables.min.css" />
<script type="text/javascript" src="https://cdn.datatables.net/v/dt/dt-1.10.22/datatables.min.js"></script>
<body>
<div class="panel panel-default">
<!-- <div class="panel-heading">Sample Data</div>-->
<div class="panel-body">
<div class="table-responsive">
<table id="sample_data" class="table table-bordered table-striped">
<thead>
<tr>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Approval</th>
<th>Roles</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
<div style="display:none;" id="select-box">
<select>
<option>Role 1</option>
</select>
</div>
</body>
its not a proper solution but it will resolve your issue. First select your roles html
var emelnt = $('#test');
//now append to table td
$('table tbody td:nth-child(6)').html(emelnt);
//you can also use a function to first get role id from table each row then create your select here in js and the append it to html so then your roles drop down will be selected.
I'm not sure if you are using DataTable or Tabledit, you seem to be mixing them for some reason. I'm not sure if this is a good idea to start with. I suggest picking one over the other. This answer focuses on Tabledit.
Since the table is essentially created and managed by Tabledit you should provide the data there. You currently already use a select for admin approval:
[4, 'admin_approved', '{"1":"Approved","2":"Disapproved"}']
Your role select can be created in a similar manner. Since the structure of $roles is not shared I will assume that it is an array with string values. First create a variable roles within your <script> tags.
const roles = <?php echo json_encode($roles); ?>;
Then add the column to the columns.editable setting:
[4, 'admin_approved', '{"1":"Approved","2":"Disapproved"}'],
[5, 'role', JSON.stringify(roles)]
You might have to convert the structure of $roles to create the correct JSON output. Here are some example results:
Example #1
// assumed <?php echo json_encode($roles); ?> output
const roles = ["role A", "role B"];
Creates:
<option value="0">role A</option>
<option value="1">role B</option>
Example #2
// assumed <?php echo json_encode($roles); ?> output
const roles = {"role_a": "role A", "role_b": "role B"};
Creates:
<option value="role_a">role A</option>
<option value="role_b">role B</option>
Take a look at how to add a row in datatables.net...
var t = $('#example').DataTable();
t.row.add( [
counter +'.1',
counter +'.2',
counter +'.3',
counter +'.4',
counter +'.5'
] ).draw( false );
So, in your case, within onSuccess:function(data, textStatus, jqXHR), we should just be able to change this, $('#sample_data').DataTable().ajax.reload();, to....
var t = $('#sample_data').DataTable();
t.row.add([
$('#test').html()
]).draw(false);
t.ajax.reload();
This is basically doing what your code was doing before, but now you're also calling the .row.add() on the DataTable().
Related
I am having trouble getting Datables to work.
No-matter what I try, I am getting the issue that there is no data.
The message exactly is: "No matching records found".
I am using the correct format found here on the official website but it doesn't seem to want to load.
I am not using MYSQL so haven't include any SPP, but am just returning the array of address's inside an array then encoding it in JSON.
In my frontend file, I am trying to load all address's from a certain router:
<script type="text/javascript">
$(document).ready(function() {
$('#table').DataTable({
"serverSide": true,
"processing": true,
"ajax": {
"url": "<?=url('database/addresses');?>",
"dataSrc": "",
},
'columnDefs': [{
'targets': 1,
'checkboxes': {
'selectRow': true
}
}],
'select': {
'style': 'multi',
'selector': 'td:first-child'
},
'order': [[5, 'desc']],
"columns": [
{ "data": "id" },
{ "data": "id" },
{ "data": "input_address" },
{ "data": "destination_address" },
{ "data": "callback_url" },
{ "data": "dateCreated.date" },
{ "data": "id" }
],
'colReorder': true
});
} );
</script>
My html table:
<form method="post" id="deleteMulti" class="ajax-multi" action="<?=url('XhPCrvFtQuE7gPP6/addresses/delete/selected');?>">
<?= csrf() ?>
<div class="row">
<div class="col-xxl-12">
<div class="card">
<div class="card-header">
<h4 class="card-title">Addresses [ <?=$count;?> ]</h4>
<div class="right fr">
<button class="btn tooltip" style="display: inline;" name="deleteSelected" title="Delete Selected Addresses"><i class="fa fa-trash" style="color: black;"></i></button>
</div>
</div>
<div class="card-body">
<div class="table-responsive">
<table id="table" class="display">
<thead>
<tr>
<th>#</th>
<th><input type="checkbox" class="" id="checkAl"></th>
<th>Input Address</th>
<th>Output Address</th>
<th>Callback Url</th>
<th>Created</th>
<th><i class="bi bi-archive-fill"></i></th>
</tr>
</thead>
<tfoot>
<tr>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
</tfoot>
</table>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
**And in my database/addresses to load the database content:**
// This is used for when we need to load more address's to the admins /addresses page
public function getAddresses() {
define('PAGE_NAME', 'Admin Addresses');
// Skip 100 as we will start from the 100th row
// We set the limit to 100 in Admin page so the page loads 100 much faster
// We will push more and more using this function inside here for when they click load more
$addresses = \r\table('addresses')->orderBy(array('index' => \r\desc('dateCreated')))->skip(100)->limit(100)->run($this->conn);
$addresses = $addresses->toArray();
$count = count($addresses);
$theArr = array();
foreach ($addresses as $address) {
$theArr[] = $address;
}
$final = array(
'draw' => 1,
'recordsTotal' => $count,
'recordsFiltered' => $count,
'data' => array_values($theArr)
);
if($count > 0) {
echo json_encode($final, JSON_FORCE_OBJECT);
} else {
return false;
}
}
My issue is that it keeps showing me:
No matching records found eventhough I do have over 4k records in there.
Take a look at this picture here
Take a look at the format of the json returned from my getAddresses():
here
I am using two fields from the table. I can get first-row value, then I added second-row value but can't get second-row value. I need if I add multiple rows, I can get all value using JSON .can you please solve these issues.
HTML:
<button class="add">Add</button>
<table class="orders-detail table table-striped table-bordered row-border hover" width="100%">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
</tr>
</thead>
<tbody></tbody>
</table>
<button class="send">Send</button>
Script:
$("document").ready(function(){
$(".add").click(function(){
var td_add="<tr><td><input type='text' id='name' class='name'></td><td><input type='text' id='age'></td></tr>";
$("tbody").append(td_add);
});
$(".send").click(function(){
var name=document.getElementById("name").value;
var age=document.getElementById("age").value;
var obj={
name:name,
age:age
};
alert(JSON.stringify(obj));
});
});
Output: i can get single row value.
{"name":"aravind","age":"42"}
i have fixed your code please check it.
$("document").ready(function() {
$(".add").click(function() {
var td_add = "<tr><td><input type='text' name='aa' id='name' class='name'></td><td><input type='text' name='bb' id='age'></td></tr>";
$("tbody").append(td_add);
});
$(".send").click(function() {
var asa = [];
$("input[name*='aa']").each(function(key, item) {
if (!asa[key]) asa[key] = {};
asa[key].calvalue = item.value;
});
$("input[name*='bb']").each(function(key, item) {
if (!asa[key]) asa[key] = {};
asa[key].calvalue2 = item.value;
});
alert(JSON.stringify(asa));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<button class="add">Add</button>
<table class="orders-detail table table-striped table-bordered row-border hover" width="100%">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
</tr>
</thead>
<tbody></tbody>
</table>
<button class="send">Send</button>
Reason:
You will always get the value of the first row because on dynamically adding rows, you are keeping same id and name for all input elements.
Solution:
Use class instead of id to get the element's value in a loop.
e.g
var names = document.getElementsByClassName("name");
for(var i = 0; i < names.length; i++)
{
names[i].value
}
Or, use this one, creating an array of objects in the form of
dat = [
{
"name": "Charlie Brown",
"age": "13"
},
{
"name": "Peppermint Patty",
"age": "11"
}
]
var tr_add="<tr><td><input type='text' name='name'></td><td><input type='text' name='age'></td><td><select name='gender'><option>female</option><option>male</option></select></td><th><input type='text' name='shoesize'></th></tr>";
$(function(){
$(".add").click(function(){ $("tbody").append(tr_add); });
$(".send").click(function(){
var dat=$("#myform").serializeArray().reduce(function(a,v){
if (v.name=='name') a.push({name:v.value}); // add new object to array
else a[a.length-1][v.name]=v.value; // add attribute to existing object
return a;
},[])
console.log(dat); });
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<button class="add">Add</button><form id="myform">
<table class="orders-detail table table-striped table-bordered row-border hover" width="100%">
<thead><tr><th>Name</th><th>Age</th><th> gender</th><th>shoe size</th></tr></thead>
<tbody></tbody>
</table></form>
<button class="send">Send</button>
The data can be extended without having to change anything in the script. It will collect all the data according to the name attribute of the input element.
The only "fixed" point in this script is that the first input field must be the one with name="name". This will trigger the creation of a new object in the dat-array.
I need to loop through datatable, find a record with specyfic id, and the update it (only this one).
<table id="data_tables">
<thead>
<tr>
<td value="id">id_value</td>
<td>Name</td>
<td>Surname</td>
<tr>
</thead>
<tbody>
<!-- Datarow 1 -->
<tr>
<td value="1">1</td>
<td>John</td>
<td>Wayne</td>
</tr>
<!-- Datarow 2 -->
<tr>
<td value="2">2</td>
<td>Clark</td>
<td>Kent</td>
</tr>
<!-- Datarow 3 -->
<tr>
<td value="3">3</td>
<td>John</td>
<td>Romero</td>
</tr>
</tbody>
</table>
And the js code. It must be datatble based becouse standard looping will not work with datatable paging (or at least it didn't work form me).
var counter = 0; //to tell me if rows numer is fine
var table = $('#data_tables').DataTable(); //to grab anchor to datatable again
//datatable way
table.rows().every( function () {
counter = counter + 1;
//I don't know how to adress current row in a loop in datatable api
if(current_row.value_or_content == 10){
current_row[1].value = 'New Name';
current_row[1].value = 'New Surname';
}
} );
alert(counter); //that is why I know that looping works ok
table.draw(); //to keep filters ok
This is how I tried, but anyway would be good. Propably even better without looping (speed issues if the is LOTS of data in datatable?)
You could pass additional parameters in the function callback for the rows().every() api. Use the rowIdx to monitor and check the index of the row of the table and then delete it.
If you want to access the row's data, you can use this.data(). It will return an array containing the row's data. For example, if the current row is the first one, the returned data should be:
[
"1",
"John",
"Wayne"
]
$(document).ready(function() {
const table = $('#data_tables').DataTable(); //to grab anchor to datatable again
//datatable way
table.rows().every(function(rowIdx, tableLoop, rowLoop) {
// The checks the id of the current row
if (this.data()[0] === "1") {
console.log(`This is row number ${rowIdx+1}`);
console.log(`This is this row's data:`);
console.log(this.data());
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.js"></script>
<table id="data_tables" cellspacing="1">
<thead>
<tr>
<th value="id">id_value</th>
<th>Name</th>
<th>Surname</th>
</tr>
</thead>
<tbody>
<!-- Datarow 1 -->
<tr>
<td value="1">1</td>
<td>John</td>
<td>Wayne</td>
</tr>
<!-- Datarow 2 -->
<tr>
<td value="2">2</td>
<td>Clark</td>
<td>Kent</td>
</tr>
<!-- Datarow 3 -->
<tr>
<td value="3">3</td>
<td>John</td>
<td>Romero</td>
</tr>
</tbody>
</table>
You don't need to do all the tedious HTML handwritting, you may source your table using javascript object (that's what I did in the following example).
You're right, there is an embedded iterator over DataTables rows, it is every() method.
What you need to do is, basically, grab necessary record, modify it, rows().remove() old record, row.add() the new one and do re-draw().
Here is the DEMO:
//Define source data
var dataSrc = [
{id:1, name: 'John', lastname: 'Wayne'},
{id:2, name: 'Clark', lastname: 'Kent'},
{id:3, name: 'John', lastname: 'Romero'},
];
//Define DataTable object
var dataTable = $('#data_tables').DataTable({
sDom: 't',
data: dataSrc,
columns: [
{title: 'id', data: 'id'},
{title: 'name', data: 'name'},
{title: 'lastname', data: 'lastname'},
]
});
//Create dynamically interface for editing
$('body').append(`
<div id="editingform" style="display:none">
<select id="idselector">
<option value="" disabled selected>id</option>
</select>
</div>
`);
//Append fields that correspond to table columns minus id column
dataTable.columns().every(function(){
if(this.dataSrc() == 'id') return;
$('#editingform').append(`
<input class="fieldsinput" datasrc="${this.dataSrc()}" placeholder="${this.dataSrc()}"></input>
`);
});
//Populate id select with possible options
$.each(dataTable.column(0).data(), function(index, value){
$('#idselector').append(`
<option value="${value}">${value}</option>
`);
});
//Append 'Edit' button and make editing form visible
$('#editingform').append(`<button id="editbutton">Edit</button>`);
$('#editingform').show();
//Listen for id selection and populate input fields
$('#idselector').on('change', function(){
//Grab row with matching 'id' value
let rowData = dataTable.rows(`:has(td:eq(0):contains('${$(this).val()}'))`).data()[0];
//Update input fields
$.each(rowData, function(index, value){
$(`input[datasrc="${index}"]`).val(value);
});
})
//Change source data upon 'Edit' button click and redraw dataTable
$('#editbutton').on('click', function(){
//Prepare new entry
let newEntry = {id:$('#idselector').val()};
$.each($('.fieldsinput'), function(){
newEntry[$(this).attr('datasrc')] = $(this).val();
});
//Remove corresponding column, add new and redraw
dataTable.rows(`:has(td:eq(0):contains("${newEntry.id}"))`).remove();
dataTable.row.add(newEntry);
dataTable.draw();
});
<!doctype html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
</head>
<body>
<table id="data_tables"></table>
</body>
I am using: jquery.dataTables.js from: https://datatables.net
I want to do 2 things:
How can I make my rows be drag and drop? any ideas? or Row reordering
right now the rows is not following the order number like: 1,2,3,4,5, how can i make the rows follow the number orders?
I found this sample: https://jsfiddle.net/gyrocode/0308ctqp/ but I could not make work on my code.
Edit:
jsfiddle answer running here:
see answer bellow
html:
<div class=" dashboard">
<div class="col-md-8 no-padding">
<div class="form-group col-md-4 no-padding">
<select class="form-control" id="sel1">
<option value="Filter by">Filter by country </option>
<option value="All">All</option>
<option value="China">China</option>
<option value="EUA">EUA</option>
<option value="Spain">Spain</option>
</select>
</div>
</div>
<br>
<br>
<table id="example" class="display" width="100%" cellspacing="0">
<thead>
<tr>
<th>First name</th>
<th>Place</th>
<th>Order</th>
</tr>
</thead>
</table>
jquery:
$(document).ready(function() {
var dt = $('#example').dataTable();
dt.fnDestroy();
});
$(document).ready(function() {
var url = 'http://www.json-generator.com/api/json/get/clmDuyndua?indent=2';
var table = $('#example').DataTable({
ajax: url,
columns: [{
data: 'name'
}, {
data: 'name'
},{
data: 'order'
}]
});
$('#sel1').change(function() {
if (this.value === "All") {
table
.columns(1)
.search('')
.draw();
} else {
table
.columns(1)
.search(this.value)
.draw();
}
});
});
this is my jsfiddle
thanks
For the reordring import required lib : (jquery-ui.js - jquery.dataTables.rowReordering.js )
And for reordering order , when using rowReordering by default the first row is used to order table , so make the order field as first in column data , otherwise I think (It's possible to use dataTable.editor.js )
Bellow a working sniipet
$(document).ready(function() {
var dt = $('#example').dataTable();
dt.fnDestroy();
});
$(document).ready(function() {
var url = 'https://www.json-generator.com/api/json/get/clmDuyndua?indent=2';
var table = $('#example').DataTable({
ajax: url,
createdRow: function(row, data, dataIndex){
$(row).attr('id', 'row-' + dataIndex);
},
rowReorder: {
dataSrc: 'order',
},
columns: [
{
data: 'order'
},{
data: 'name'
},{
data: 'place'
}]
});
table.rowReordering();
$('#sel1').change(function() {
if (this.value === "All") {
table
.columns(1)
.search('')
.draw();
} else {
table
.columns(1)
.search(this.value)
.draw();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>
<script src="//cdn.datatables.net/1.10.4/js/jquery.dataTables.min.js"></script>
<link href="//cdn.datatables.net/1.10.4/css/jquery.dataTables.css" rel="stylesheet"/>
<script src="//mpryvkin.github.io/jquery-datatables-row-reordering/1.2.3/jquery.dataTables.rowReordering.js"></script>
<div class=" dashboard">
<div class="col-md-8 no-padding">
<div class="form-group col-md-4 no-padding">
<select class="form-control" id="sel1">
<option value="Filter by">Filter by country </option>
<option value="All">All</option>
<option value="China">China</option>
<option value="EUA">EUA</option>
<option value="Spain">Spain</option>
</select>
</div>
</div>
<br>
<br>
<table id="example" class="display" width="100%" cellspacing="0">
<thead>
<tr>
<th>Order</th>
<th>First name</th>
<th>Place</th>
</tr>
</thead>
</table>
I am trying make my filter works with json data from the server, someone could help me to do this?
I need filter by places: All, EUA,China, Spain
I am using: jquery.dataTables.js from: https://datatables.net
html:
<div class=" dashboard">
<div class="col-md-8 no-padding">
<div class="form-group col-md-4 no-padding">
<select class="form-control" id="sel1" >
<option value="Filter by">Filter by country </option>
<option value="All">All</option>
<option value="First name">China</option>
<option value="Last name">EUA</option>
<option value="Last name">Spain</option>
</select>
</div>
</div>
<br>
<br>
<table id="example" class="display" width="100%" cellspacing="0">
<thead>
<tr>
<th>First name</th>
<th>Place</th>
</tr>
</thead>
</table>
jquery:
$(document).ready(function() {
var dt = $('#example').dataTable();
dt.fnDestroy();
} );
$(document).ready(function () {
var url = 'http://www.json-generator.com/api/json/get/crcCiZXZfm?indent=2';
var table = $('#example').DataTable({
ajax: url,
columns: [
{ data: 'name' },
{ data: 'place' }
]
});
});
jsfiddle:
http://jsfiddle.net/ntcwust8/120/
http://jsfiddle.net/f7debwj2/
Added the following code to your document.ready():
$('#sel1').change(function() {
if (this.value === "All") {
table
.columns(1)
.search('')
.draw();
}
else {
table
.columns(1)
.search(this.value)
.draw();
}
});
So basically you tell your SELECT element to wait for its value to be changed. In order to show ALL, the .search() parameter is set to an empty string, which will return ALL. Otherwise the dropdown will trigger a table search on column(1) with the selected VALUE (not text!) of your SELECT and redraw your table.
Note: I also changed the value properties of your SELECT, since they were wrong in the beginning.
DataTables Documentation on column().search() can be found HERE.