JQuery DataTables and Jeditable - fields contains html but should not. Why? - javascript

I am using DataTables and Jeditbale. Everything seems to work well, however, for some reason when I double-click any field within the table, it contains HTML. I have inserted the visual herein. I have not tried anything to fix this problem as I cannot even understand how this would occur. I have googled the problem but most people who report a similar problem just report extra blank spaces; not full html in fields. How can I fix this? If additional code required, can add in due course.
Here is my table code:
<!-- start table listing -->
<table id="myTable" class="stripe hover cell-border row-border">
<thead>
<tr>
<th id="country_id">Country ID</th>
<th id="country">Country Name</th>
<th id="country_import">Import Commnents</th>
<th id="country_export">Export Comments</th>
<th id="country_date_created">Created</th>
<th id="country_date_updated">Updated</th>
<th id="">Updated by</th>
<th id="country_enabled">Enabled?</th>
<th id="">Actions</th>
</tr>
</thead>
<tbody>
<?php
foreach ($query as $row ) {
?>
<tr <?php echo 'id="'.$row->country_id.'"'; ?> >
<td>
<?php echo $row->country_id; ?>
</td>
<td>
<a class='table-action-deletelink' href='/admin/country_view/<?php echo ''.$row->country_id.''; ?> '><?php echo $row->country; ?></a>
</td>
<td>
<?php echo $row->country_import_comments; ?>
</td>
<td>
<?php echo $row->country_export_comments; ?>
</td>
<td>
<?php echo $row->country_date_created; ?>
</td>
<td>
<?php echo $row->country_date_last_updated; ?>
</td>
<td>
<?php echo $row->country_updated_by; ?>
</td>
<td> <?php
if ($row->country_enabled == 1) {
echo '<span class="glyphicon glyphicon-ok" aria-hidden="true" ></span>';
} else {
echo '<span class="glyphicon glyphicon-remove" aria-hidden="true" ></span>';
} ?>
</td>
<td>
<!-- main container -->
<div class="dropdown">
<button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-expanded="true">
Dropdown
<span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu1">
<li role="presentation"><a role="menuitem" tabindex="-1" href="/admin/country_view/<?php echo ''.$row->country_id.''; ?>">View</a></li>
<li role="presentation"><a role="menuitem" tabindex="-1" href="#">Edit</a></li>
<li role="presentation"><a role="menuitem" tabindex="-1" href="#">Deactivate</a></li>
<li role="presentation"><a role="menuitem" tabindex="-1" href="/admin/country_delete/<?php echo ''.$row->country_id.''; ?> ">Delete</a></li>
</ul>
</div>
</td>
</form>
</tr>
<?php } ?>
</tbody>
</table>
</div>
</div>
</div>
Here is my javascript that implements the table:
$(document).ready(function() {
//sDeleteURL: "/Home/DeleteData.php"
$('#myTable').dataTable().makeEditable( {
// some basic config
'bProcessing': true,
'bServerSide': true,
'sAjaxSource': "admin/json_get_countries",
stateSave: true,
"scrollCollapse": true,
"language": {
"lengthMenu": "Display _MENU_ records per page",
"zeroRecords": "Nothing found - sorry",
"info": "Showing page _PAGE_ of _PAGES_",
"infoEmpty": "No records available",
"infoFiltered": "(filtered from _MAX_ total records)"
}
} );
} ); // end of on doc load

You're using jQuery DataTables Editable plugin which internally uses jQuery Jeditable plugin.
According to Jeditable documentation (see Usage with Textile, Markdown, ReST, WiKi), if field contains content other than plain text (HTML, Markdown, etc), you need to use loadurl parameter to load content in and sUpdateURL to save modified value.
See Editable DataTable example - custom editors on how Engine version field is being edited and saved by using URLs specified in loadurl and sUpdateURL parameters.
You can make certain columns read-only and not-editable by defining aoColumns option and specifying null for corresponding column. aoColumns is an array holding options for all columns in sequential order, length of this array must be equal to the number of columns in the original HTML table.
Example:
$(document).ready( function () {
$('#example').dataTable().makeEditable({
sUpdateURL: "UpdateData.php",
"aoColumns": [
null,
{
},
{
indicator: 'Saving platforms...',
tooltip: 'Click to edit platforms',
type: 'textarea',
submit:'Save changes',
fnOnCellUpdated: function(sStatus, sValue, settings){
alert("(Cell Callback): Cell is updated with value " + sValue);
}
},
{
//indicator: 'Saving Engine Version...',
tooltip: 'Click to select engine version',
loadtext: 'loading...',
type: 'select',
onblur: 'cancel',
submit: 'Ok',
loadurl: 'EngineVersionList.php',
loadtype: 'GET',
sUpdateURL: "CustomUpdateEngineVersion.php"
},
{
indicator: 'Saving CSS Grade...',
tooltip: 'Click to select CSS Grade',
loadtext: 'loading...',
type: 'select',
onblur: 'submit',
data: "{'':'Please select...', 'A':'A','B':'B','C':'C'}",
sUpdateURL: function(value, settings){
alert("Custom function for posting results");
return value;
}
}
]
});
})
See answer to similar problem with Jeditable. However this answer targets Jeditable only and not jQuery DataTables Editable plugin, so the code shown there doesn't apply, just the explanation.

Related

show/hide icons in div in table row using jquery

I have a table, its is data displayed using foreach. one column have 3 icons, by default they are hidden. And also have checkbox. icons and checkbox are in every row. Now when select any checkbox, icons of all rows are appearing. Instead I want only one row icons should be displayed on selecting checkbox. Can somebody help please. thanks in advance. here is the code.
in view
<?php $sn= $this->uri->segment(4); foreach($companies as $company){ $sn++;?>
<tr class="parent" style="font-size:11px;color:#3D4061;border-bottom:1px solid #3d406136">
<td><input type="checkbox" class="text-center check_data mt-2" onchange="changevalue()"></td>
<td class="text-center" style=""><h6><?php echo $sn; ?></h6></td>
<td class="text-center" style=""><h6><?php echo $company->company_name; ?></h6></td>
<td class="text-center" style=""><h6><?php echo $company->contact_no; ?></h6></td>
<?php if($company->activation_status == 1){?>
<td class="text-center" style=""><h6 class="text-success font-weight-bold" style="font-size:13px">Active</h6></td>
<?php } ?>
<?php if($company->activation_status == 0){?>
<td class="text-center" style=""><h6 class="text-danger font-weight-bold" style="font-size:13px">Inactive</h6></td>
<?php } ?>
<td class="text-center" style="">
<div class="status">
<i class="fa fa-edit"></i>
<?php if($company->activation_status == 0){?>
<i class="fa fa-dot-circle-o"></i>
<?php }else{ ?>
<i class="fa fa-exclamation-triangle"></i>
<?php } ?>
<i class="fa fa-trash-alt"></i>
</div>
</td>
<td ><i class="fa fa-chevron-down down" ></i></td>
</tr>
and script is
<script>
$('.status').hide();
function changevalue(){
if($(".check_data").is(":checked"))
$('.status').show();
else
$(".status").hide();
$('.cchild').hide();
}
</script>
you can also use .parent() and .find() methods to get specific row like that:
<input type="checkbox" function="changevalue(this)">
and your javacript must be like that:
function changevalue(elem){
if($(elem).is(":checked"))
$(elem).parent().parent().find('.status').show();
else
$(elem).parent().parent().find('.status').hide();
}
This code can be simplified but it's a good starting example to understand parent-child usage of html elements. At this example first .parent() goes to <td> of checkbox element and second .parent() goes to <tr> element then it searches for .status class in it then hides it.
and you can simplfy it like that:
function changevalue(elem){
if($(elem).is(":checked"))
$(elem).parents("tr").find('.status').show();
else
$(elem).parents("tr").find('.status').hide();
}
function changevalue() {
var $this = $(this),
$status = $this.parents("tr").find(".status");
if ($this.is(":checked")) {
$status.show();
} else {
$status.hide();
}
}
You can give dynamic Ids to every checkbox and status div. Use your record's id may be companyId to create Ids like
<input type="checkbox" id="checkbox_('<?php echo $company->id; ?>')>
I don't know the syntax for php.
and then you can pass the current companyId in onchange="changevalue(companyId)"
and then your code will be like this
function changevalue(companyId){
if($("#checkbox" + companyId).is(":checked"))
$('#status' + companyId).show();
else
$("#status" + companyId).hide();
}

Get content of an element contains a string and select it

I'm looking for a way to search for a string in a table rows by jquery and get all of that contents and select the element that have it to get the other pieces!
here is the html side:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Tel</th>
<th>Description</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php
$allcontacts=$contact->getallcontacts("name",$_SESSION['username']);
if($allcontacts!=null)
foreach($allcontacts as $value){
?>
<tr>
<td class="contact-id">
<?php echo $value[0]; ?>
</td>
<td class="contact-name">
<?php echo $value[1]; ?>
</td>
<td class="contact-tell">
<?php echo $value[2]; ?>
</td>
<td class="contact-info">
<?php echo $value[3]; ?>
</td>
<td class="td-actions">
<a href="?IDD=<?php echo $value[0]." &owner=".$_SESSION['username'];?>">
<i class="glyphicon glyphicon-trash"></i>
</a>
<a href="#" class="eb" data-uid="<?php echo $value[0]; ?>" data-toggle="modal" data-target=".bs-example-modal-lg">
<i class="glyphicon glyphicon-edit"></i>
</a>
<a href="#" onclick="" class="se">
<i class="glyphicon glyphicon-envelope"></i>
</a>
</td>
</tr>
<?php } ?>
</tbody>
</table>
<input type="text" class="cs" /><input type="button" value="Search" class="csb"/>
here is the script side!
$(".csb").click(
function() {
var ss = $(".cs").val();
var farray = $("td:contains(ss)").toArray();
console.log(farray);
}
);
console gets me an empty array!
ok ive tried ur code, obiously without php, so i put plain info. maybe this will help u
$(".csb").click(function(){
var ss = $(".cs").val();
var farray = new Array(); //define array
$("tr").removeAttr("style"); //reset all
if(ss!=""){ //check if isnt empty
$("td:contains("+ss+")").each(function(){
$(this).parent().css("background","red"); //select found
//push to array
farray.push($(this).parent().find(".contact-id").html());
farray.push($(this).parent().find(".contact-name").html());
farray.push($(this).parent().find(".contact-tell").html());
farray.push($(this).parent().find(".contact-info").html());
});
}
else{
alert("put a text");
}
//result
$("code").html("value search: "+ss);
$("pre").html("id found: "+farray[0]+"<br>"+
"name found: "+farray[1]+"<br>"+
"tel found: "+farray[2]+"<br>"+
"info found: "+farray[3]);
});
this is the full code: https://jsfiddle.net/keejke5e/3/
You don't need to add .toArray() as $("td:contains(ss)") returns array. I think you need to check whether you getting $("td") element or not. As for I see, according to your code it should find it. So just check $("td") and $("td:contains(ss)") in your chrome console.

Getting user from db and appending to element

This might be a simple question but have kept me busy for the best part of a hour.
I have the following script which generates all active reservations, in the table reservations
require("../includes/connect.php");
function dispAllReservations(){
$i= 1;
global $db;
$date = date('Y-m-d');
$sql ="SELECT * FROM
reservations WHERE pickup_date > '$date'";
$statement = $db->prepare($sql);
$statement->execute();
$bookings = $statement->fetchAll();
$statement->closeCursor();
echo'<table cellpadding="0" cellspacing="0" class=
"table-responsive gzblog-table" id="gzhotel-booking-booking-id">
<thead>
<tr>
<th class="date-th">Reservation ID</th>
<th class="title-th">Car Group</th>
<th>Pickup Date</th>
<th>Return Date</th>
<th>Customer</th>
<th>Email</th>
<th>Amount</th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>';
foreach($bookings as $booking){
if($i%2 == 0){
$class = 'odd';
}
else{
$class = 'even';
}
echo' <tr class='.$class.'>';
echo'<td>'.$booking['res_id'].'</td>';
echo'<td>'.$booking['car_group'].'</td>';
echo'<td>'.$booking['pickup_date'].'</td>';
echo'<td>'.$booking['return_date'].'</td>';
echo'<td>'.$booking['renter_name'].'</td>';
echo'<td>'.$booking['email'].'</td>';
echo'<td>AMOUNT HERE</td>';
echo'<td><a class="btn btn-primary btn-sm fancybox" href="#email">
<span class="glyphicon glyphicon-envelope"></span></a>
</td>';
echo'<td><a class="btn btn-success btn-sm">
<span class="glyphicon glyphicon-pencil"></span></a>
</td>';
echo'<td><a class="btn btn-danger btn-sm icon-delete">
<span class="glyphicon glyphicon-trash"></span></a>
</td>';
echo'</tr>';
}//foreach
echo'</tbody>';
echo'</table>';
}//function
The output of the script generates the following
My Problem / Question
When delete button is clicked -- I need to ensure the correct reservation is deleted, same with the edit button, if edit button is clicked I need to ensure the correct user is edited.
What I need to do
I'm guessing I would need to find a way to append the corresponding value for each user in the loop to the element.
I was thinking of a textbox setting display none and then echoing the value inside the value attribute, but that didn't work...
I'm really stuck here any advise would be appreciated
NOTE: All emails are fictional
Try this:
<a class="btn btn-primary btn-sm fancybox" href="#email" onclick="onDelete(your-id)">
<span class="glyphicon glyphicon-trash"></span>
</a>
<a class="btn btn-primary btn-sm fancybox" href="#email" onclick="onEdit(your-id)">
<span class="glyphicon glyphicon-pencil"></span>
</a>
Create this function:
<script>
//Delete function
function onDelete(id){
$.ajax({
// do someting
});
}
// Edit function
function onEdit(id){
$.ajax({
// do someting
});
}
</script>
You did not tell us at all how do you want to edit/delete you reservations, but based on the tags you used you can take this approach...
1) In your PHP script generate data attributes on rows or cells, like this:
<tr data-id="put_reservation_id_here">
2) And then use jQuery to hook actions to various elements in the table:
$('#gzhotel-booking-booking-id').on('click', '.icon-delete', function() {
var reservationId = $(this).closest('tr').data('id');
// now you have reservation ID and do whichever AJAX call with it
});
You can use data attributes in your html and then get the data attribute value using javascript.
Example:
In your button:
<a class="btn btn-danger btn-sm icon-delete" data-id="your_Id"><span class="glyphicon glyphicon-trash"></span></a>
Replace your_Id with the correct id.
Then using javascript on your onClick event:
$(this).data('id');
This will retrieve the id that you need to handle the action.
Hope this helps.

jQuery DataTables inline editing of empty fields

So far this is my set-up of DataTables used in my own app:
But the input fields are not that UI-friendly or pleasing to look at. And so I happen to stumble upon this feature of DataTable, which is Inline Editing, and now instead of those unpleasant-looking input fields, I want to have the fields similar to the Inline Editing functionality of Data Tables, with the exception that there are no values "to be edited", just empty fields with placeholder texts.
Is that even possible? I tried to trace the example and it seems to make use of some DataTable.Editor, but I can't seem to grasp how to implement an empty field one instead of a "editable field with default contents" (like the examples found in the documentations).
Any help? Also, if appreciated, I'd like to have the Total Load to automatically be computed whenever the No. of Units and Power Rating is filled up. It is simply the (No. of Units * Power Rating).
Here's my initial code setup:
The table.js contains the initialization of the DataTables,
whilst globs.js contains the ajax query with the corresponding creation of rows in the table.
I just pasted the codes that are relevant to my questions, and disregarded the others (jQuery actions of the buttons and etc)
table.js (Initialized jQuery codes)
$(function() {
var table = $('#costcenter_table').DataTable({
"columnDefs": [
{
"targets": 4,
"visible": false,
"searchable": false,
"sortable": false,
"width": "75px"
}
]
});
});
globs.js (contains functions with Ajax queries)
function show_cost_tables(costcenter){
$.ajax({
url: '/costcenter/' + costcenter,
type: 'GET',
dataType: 'json',
async: true,
success: function(res){
if(res.status === "success"){
$('#costcenter_table').DataTable().clear();
for(var i = 0; i < res.count; i++){
var entry = res.data[i];
var buttons = '<div style="text-align: center;"><button class="btn btn-xs btn-primary add-unit"><span class="fa fa-plus"></span></button> ' +
'<button class="btn btn-xs btn-warning remove-unit"><span class="fa fa-minus"></span></button> ' +
'<button class="btn btn-xs btn-danger delete-load"><span class="fa fa-close"></span></button></div>';
$('#costcenter_table').DataTable().row.add([entry.name, entry.unit_count, entry.power_rating, entry.total_load, buttons]).draw();
}
} else {
console.log(res.status + " login details.");
$('#warning-login').modal('toggle');
}
}
});
}
table.html (the input fields at the footer here should be gone and be replaced by that Inline Edit fields of DataTables)
<table id="costcenter_table" class="table table-bordered table-striped" cellspacing="0" width="100%">
<thead>
<tr>
<th>Load</th>
<th>No. of Units</th>
<th>Power Rating</th>
<th>Total Load</th>
<th></th>
</tr>
</thead>
<tbody id ="costcenter_data">
</tbody>
<tfoot id="add-new-load" style="display: none;">
<tr>
<form id="new-load" role="form">
<th><input id="name" name="name" type="text" placeholder="Load Name"><br><br><input id="brand" name="brand" type="text" placeholder="Brand"></th>
<th><input id="unit_count" name="unit_count" type="text" placeholder="No. of Units"><br><br><input id="location" name="location" type="text" placeholder="Location"></th>
<th><input id="power_rating" name="power_rating" type="text" placeholder="Power Rating"></th>
<th><input id="total_load" placeholder="Total Load" type="text" disabled></th>
<th><button id="add-load" class="btn btn-primary add-load" >Add New Load</button></th>
</form>
</tr>
</tfoot>
</table>
PS. Please try to ignore the last two input fields (Brand and Location), they are supposed to be dropdowns and browse buttons respectively.

sending jQuery sortable data via ajax

I am working with jQuery Sortable and twitter bootstrap as well. I have table rows that I am trying to sort. The drag and drop is working fine but I am trying to send the new sort order via ajax which is not picking up/sending the sort order and when i try to alert the data it seems empty.
This is my PHP code which is using loop to pull the records from MySQL
<table class="table table-striped table-bordered ">
<thead>
<tr>
<th> Slide Title</th>
<th> Action</th>
</tr>
</thead>
<tbody>
<?php
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
?>
<tr id="<?php echo $row['id']; ?>">
<td>
<?php echo $row['title']; ?>
</td>
<td>
<div class="btn-group pull-right">
<button data-toggle="dropdown" class="btn btn-small btn-info dropdown-toggle">
Action<span
class="caret"></span></button>
<ul class="dropdown-menu">
<li>Edit
</li>
<li>
Delete
</li>
</ul>
</div>
</td>
</tr>
<?php
}
?>
</tbody>
</table>
and this is the java script that is doing the sorting and then sending data to a file called slides.php
$(document).ready(function(){
$(function() {
$('table').sortable({
items: 'tr',
opacity: 0.6,
axis: 'y',
stop: function (event, ui) {
var data = $(this).sortable('serialize');
alert(data);
$.ajax({
data: data,
type: 'POST',
url: 'slides.php'
});
}
});
});
});
What I feel is my variable data var data = $(this).sortable('serialize'); is not working, if i send a static variable then I am able to see that in $_POST
I will really really appreciate any assistance in this.
I ended up following up the concept mentioned on this link to do my task, for some reason current solution was not working with <table> so I just re wrote the html part using <ul></ul> and it worked.
I hope this helps anyone out there having the same problem.

Categories

Resources