I am trying to create dynamic td elements using Datatables from an AJAX feed.
Here is the relevant aoColumnDefs for the column:
"aoColumnDefs": [
{
"mRender":function(data, type, row) {
return '<td class="ms">' +
'<div class="btn-group1">' +
'<a class="btn btn-small" rel="tooltip" data-placement="left" data-original-title="Edit">' +
'<i class="gicon-edit"></i>' +
'</a> ' +
'<a class="btn btn-small" rel="tooltip" data-placement="top" data-original-title="View">' +
'<i class="gicon-eye-open"></i>' +
'</a>' +
'<a class="btn btn-small" rel="tooltip" data-placement="bottom" data-original-title="Remove">' +
'<i class="gicon-remove"></i>' +
'</a>' +
'</div>' +
'</td>';
},
"aTargets":[7]
},
As you can see I need to process this after the row is created to apply the bootstrap.tooltips plugin to the <a> elements.
Here is what I have tried, amongst other combinations of jQuery selectors:
"fnCreatedRow": function(nRow, aData, iDataIndex) {
$("a").tooltip();
},
Nothing I have tried has worked in attempting to get the plugin to enhance my buttons and have the tooltips appear on hover, they have the correct CSS so they aren't invisible because this exact HTML and CSS works in a static HTML file without the dynamic creation of the elements.
I believe you can make tooltips work with an ajax data source by using mRender and fnCreatedCell. Note the datatables reference page and compare fnCreatedCell with fnCreatedRow.
HTML
<table id="example" class="table table-condensed">
<thead>
<tr>
<th>Vegetable</th>
<th>Fruit</th>
<th>Options</th>
</tr>
</thead>
<tbody></tbody>
</table>
JavaScript (or at least the pertinent part of calling datatables)
$('#example').dataTable({
"aaData": aaData,
// other set up for datatables left out for the sake of getting to the main issue...
"aoColumnDefs": [
{ "aTargets": [0],
"mData": "VegetableName",
"sWidth": "150px"
},
{ "aTargets": [1],
"mData": "FruitName",
"sWidth": "150px"
},
{ "aTargets": [2],
"mData": "LoansOpenedThisDay",
"mRender": function (data, type, full) {
// Note:
// not manually coding the '<td>' as in the question.
return '<div class="btn-group1">' +
'<a class="btn btn-small" rel="tooltip" data-placement="left" data-original-title="Edit">' +
'<i class="gicon-edit"></i>' +
'</a> ' +
'<a class="btn btn-small" rel="tooltip" data-placement="top" data-original-title="View">' +
'<i class="gicon-eye-open"></i>' +
'</a>' +
'<a class="btn btn-small" rel="tooltip" data-placement="bottom" data-original-title="Remove">' +
'<i class="gicon-remove"></i>' +
'</a>' +
'</div>';
},
"fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
// console.log( nTd );
$("a", nTd).tooltip();
}
}
],
// more datatables set up...
Related
I've setup a jQuery add/update/delete table which uses ajax calls to controller. Some of the data fields are null.
Is there a way to write this JavaScript code to show empty value if database value returned is null?
Here's the ajax call to the controller, with the data returned to complete the table.
let html = '' +
'<tr>'+
'<td class="fw-normal">'+data.id+'</td>'+
'<td class="fw-normal">'+data.employment_type+'</td>'+
'<td class="fw-normal">'+data.start_date+'</td>'+
'<td class="fw-normal">'+data.end_date+'</td>'+
'<td class="fw-normal">'+data.state+'</td>'+
'<td class="fw-normal">'+data.city+'</td>'+
'<td>'+
'<form action="'+data.delete_url+'" method="post">'+
'#csrf'+
'#method('DELETE')'+
'<div class="btn-group">'+
'ویرایش'+
'<button type="submit" class="btn btn-danger btn-sm job-destroy">حذف</button>'+
'</div>'+
'</form>'+
'</td>'+
'</tr>';
$('#showJobs').append(html);
Note: I want to did not show ward of null.
Consider the following example code.
function checkNull(string) {
if (string === null) {
string = ""
}
return string;
}
function addRow(data) {
var row = $("<tr>");
$.each(data, function(key, value) {
if (key != "delete_url" || key != "edit_url") {
$("<td>", {
class: "fw-normal"
}).html(checkNull(value)).appendTo(row);
}
});
$("<td>").appendTo(row);
$("<form>", {
action: data.delete_url,
method: "post"
}).appendTo($("td:last", row));
$("<div>", {
class: "btn-group"
}).appendTo($("form", row));
$("<a>", {
href: data.edit_url,
class: "btn btn-info btn-sm"
}).html("ویرایش").appendTo($(".btn-group", row));
$("<button>", {
type: "submit",
class: "btn btn-danger btn-sm job-destroy"
}).html("حذف").appendTo($(".btn-group", row));
return row;
}
$('#showJobs').append(addRow(myData));
If you add some small functions, you can easily use them to ensure that null does not appear in your HTML.
Datatable on change ajax on checkbox not working, I have a data table and i am trying to update the value of active in the table into 1 if the checkbox is clicked, and 0 if clicked again. It is not even displaying the console log that i have inserted, I do not where to start. Thank you in advance for any help
ShopsController:
public function activeswitch(){
DB::table('shops')
->update(['active'=>1]);
}
blade.php:
<script>
$(document).ready(function () {
table = $('#shops_table').DataTable({
"processing": true,
"serverSide": true,
"ajax": "{{url('api/admin/shops/get-shops')}}",
rowId: "id",
stateSave: true,
dom: 'Bfrtip',
"buttons": [
'excelHtml5',
'pdf',
'print'
],
"order": [[ 0, "desc" ]],
columns: [
{data: 'id'},
{data: 'name'},
{data: 'image', render: function(data){
return "<img src='/storage/uploads/logo/" + data + "' width=auto height='50' />"
}},
{data: 'color'},
{data: 'switch', render: function(data){
return '<label class="switch">' +
' <input type="checkbox" class="checkbox">' +
'<span class="slider round" data-active-value=0>' +
' </span>' +
' </label>';
}},
{data: 'id', 'width' : '10%', render: function(data){
return '<div class="action-buttons">' +
'<i class="fa fa-eye"></i>' +
'<i class="fa fa-pencil"></i>' +
' <form action="shops/'+data+'" method="POST" style="display: inline-block;">' +
'<input type="hidden" name="_method" value="DELETE" />' +
' #csrf' +
'<button class="btn btn-xs btn-rounded btn-danger" type="submit"><i class="fa fa-trash"></i></button>' +
' </form>' +
'</div>';
}}
],
});
});
$( document ).ready(function() {
$(".checkbox").change(function(e){
console.log('hi')
e.preventDefault();
var selct_ = $(this) //declare this
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: "{{ route('active.switch') }}",
data:{
'active':$(this).data('active-value')
},
type: "get",
success: function(result){
console.log('hi')
}
});
});
});
</script>
It's not working because you're adding listeners to elements that don't exists yet.
Datatables.js has a callback that runs once it's been drawn, try this:
$(document).ready(function () {
table = $('#shops_table').DataTable({
"processing": true,
"serverSide": true,
"ajax": "{{url('api/admin/shops/get-shops')}}",
rowId: "id",
stateSave: true,
dom: 'Bfrtip',
"buttons": [
'excelHtml5',
'pdf',
'print'
],
"order": [[ 0, "desc" ]],
columns: [
{data: 'id'},
{data: 'name'},
{data: 'image', render: function(data){
return "<img src='/storage/uploads/logo/" + data + "' width=auto height='50' />"
}},
{data: 'color'},
{data: 'switch', render: function(data){
return '<label class="switch">' +
' <input type="checkbox" class="checkbox">' +
'<span class="slider round" data-active-value=0>' +
' </span>' +
' </label>';
}},
{data: 'id', 'width' : '10%', render: function(data){
return '<div class="action-buttons">' +
'<i class="fa fa-eye"></i>' +
'<i class="fa fa-pencil"></i>' +
' <form action="shops/'+data+'" method="POST" style="display: inline-block;">' +
'<input type="hidden" name="_method" value="DELETE" />' +
' #csrf' +
'<button class="btn btn-xs btn-rounded btn-danger" type="submit"><i class="fa fa-trash"></i></button>' +
' </form>' +
'</div>';
}}
],
"fnDrawCallback": function() {
$(".checkbox").change(function (e) {
console.log('hi')
});
}
});
});
I am using ajax to get some students data from database. And I have separate markup inside ajax for that data to display in the table. Now what I wanna do is to get the last inserted record or the latest record on the top but I have no I idea how to do that. I use sortByDesc() function but that does not work in this case. Below is my code. Help :)
Ajax Call
var classID = $(this).val();
if (classID) {
$.ajax({
url: '/attendance/ajax/' + classID,
type: "GET",
dataType: "json",
success: function (data) {
var table = $('table[id="studentsData"]');
table.DataTable().destroy();
var markup = '';
markup = '<thead><tr><th style="width: 2%" class="align-middle text-center"><input type="checkbox" id="options"></th><th style="width: 15%" class="text-center">Student ID</th> <th style="width: 15%" class="text-center">Student Name</th> <th style="width: 15%" class="text-center">Attendance</th> <th style="width: 15%" class="text-center">Date</th> <th style="width: 15%;" class="align-middle text-center">Actions</th> </tr></thead><tbody>';
$.each(data, function (key, value) {
markup += '<tr> <td><input class="checkBoxes" type="checkbox" name="checkBoxArray[]" value="' + value.id + '"></td> <td class="text-center align-middle"><input type="hidden" value="' + value.student_id + '" name="student_id[]">' + value.student_id + '</td> <td class="text-center align-middle"><input type="hidden" value="' + value.first_name + '" name="first_name[]"><input type="hidden" value="' + value.last_name + '" name="last_name[]">' + value.first_name + ' ' + value.last_name + '<td class="text-center align-middle"><input type="hidden" value="' + value.attendance + '" name="attendance[]">' + value.attendance + '</td>' + '<td class="text-center align-middle"><input type="hidden" value="' + value.date + '" name="date[]">' + value.date + '</td>' + '<td style=" width=12%" class="text-center"> <a data-toggle="modal" data-target="#editAttendanceModal' + value.id + '"><button title="Edit" class="btn btn-primary"><span class="fas fa-pencil-alt"></span></button></a> <a data-toggle="modal" data-target="#deleteAttendanceModal' + value.id + '"><button title="Delete" class="btn btn-danger"><span class="fas fa-trash-alt"></span></button></a> </td>' + '</td> </tr>';
});
markup += '</tbody>';
var table = $('table[id="studentsData"]');
table.html(markup);
table.DataTable();
}
});
}
});
**Controller**
public function myAttendanceAjax($id) {
$students_register = StudentsAttendance::where('class_id', $id)->get();
return json_encode($students_register);
}
You can use orderBy('id', 'desc')->get(); for geting latest record.
There is a method latest() defined in Illuminate\Database\Query\Builder Class.
public function latest($column = 'created_at')
{
return $this->orderBy($column, 'desc');
}
So, It will just orderBy with the column you provide in descending order with the default column will be created_at.
For more information about sorting have a look at https://laravel.com/docs/5.8/queries#ordering-grouping-limit-and-offset
I have a problem in getting the actual values from ids. I can't understand the issue because while storing these values I am getting them using Ajax in a dropdown where it stores its ids from the dropdown. But when I am trying to get these values back, then it shows me those ids and not the actual values. I can't understand how I can get the actual values from these ids. I also plucked them in my index method in the controller, but that's not working because it's Ajax. Below is my code, please let me know if you want to know anything more about this.
Controller actions for creating the form.
public function create()
{
$classes = StudentsClass::pluck('class_name', 'id')->all();
$rep_cat = ReportCtegories::pluck('name', 'id')->all();
return view('admin.reports.create', compact('classes', 'rep_cat'));
}
public function getStudentId($id)
{
$students = DB::table("students")->where("students_class_id", $id)->pluck("student_id", "id");
return json_encode($students);
}
public function getStudentName($id)
{
$students = DB::table("students")->select("id", DB::raw("CONCAT(first_name, ' ', last_name) as name"))
->where("students_class_id", $id)->pluck("name", "id");
return json_encode($students);
}
Ajax for getting values.
<script>
$(document).ready(function () {
//FOR LOADING STUDENTS
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('select[name="class_id"]').on('change', function () {
var classID = $(this).val();
if (classID) {
$.ajax({
url: '/reports/ajax/' + classID,
type: "GET",
dataType: "json",
success: function (data) {
var markup = '';
markup = '<thead><tr class="filters"><th style="width: 2%" class="align-middle text-center"><input type="checkbox" id="options"></th><th style="width: 15%" class="text-center">Student ID<input type="text" class="form-control" disabled></th> <th style="width: 15%" class="text-center">Student Name<input type="text" class="form-control" disabled></th> <th style="width: 15%" class="text-center">Report Category<input type="text" class="form-control" disabled></th> <th style="width: 15%;" class="align-middle text-center">Actions</th> <tr></thead><tbody>';
$.each(data, function (key, value) {
markup += '<tr> <td><input class="checkBoxes" type="checkbox" name="checkBoxArray[]" value="' + value.id + '"></td> <td><input type="hidden" value="' + value.student_id + '" name="student_id[]">' + value.student_id + '</td> <td><input type="hidden" value="' + value.student_name + '" name="student_name[]">' + value.student_name + '<td><input type="hidden" value="' + value.report_categories_id + '" name="report_categories_id[]">' + value.report_categories_id + '</td>' + '<td style=" width=12%" class="text-center"> <a data-toggle="modal" data-target="#editAttendanceModal' + value.id + '"""><button title="Edit" class="btn btn-outline-primary"><span class="fas fa-pencil-alt"></span></button></a> </td>' + '</td> <tr>';
});
markup += '</tbody>';
$('table[id="studentsData"]').html(markup);
}
});
}
});
});
</script>
First of all i recommend you use,
return response()->json($students)
Second pluck only return an array of ids(in your case)
I think you can try with this.
public function getStudentId($id)
{
$students = DB::table("students")->where("students_class_id", $id)->get();
return response()->json($students);
}
I'm trying to have multiple forms inside mutiple modals, as I've read I have to use swal.mixin with queue, all of these forms have multiple inputs inside.
I've already done that, but can't find a way to validate all of these forms, any sugestion?
Here's my code:
swal.mixin({
confirmButtonText: 'Siguiente',
buttonsStyling: false,
}).queue([
{
html:
"<form class='formulario' action='' method='post'>" +
"<div class='fila'>"+
"<img src='src/images/svg/icons/person.svg' class='imagen'/>"+
"<input id='name' class='espacio-datos' name='nombre' type='text' placeholder='Nombre' maxlength='20' required>" +
"</div>"+
"<div class='fila'>"+
"<img src='src/images/svg/icons/id.svg' class='imagen'/>"+
"<input id='ced' class='espacio-datos' name='num_ident' type='text' placeholder='Cedula' onkeypress='onlyNumbers(event)'>" +
"</div>"+
"<div class='fila'>"+
"<img src='src/images/svg/icons/phone.svg' class='imagen'/>"+
"<input id='tlf' class='espacio-datos' name='num_telef' type='text' placeholder='Telefono' onkeypress='onlyNumbers(event)'>" +
"</div>"+
"</form>",
preConfirm: function () {
var array = {
'nombre' : $("#name").val(),
'cedula' : $("#ced").val(),
'telefono' : $("#tlf").val(),
}
return array;
},
},
{
html:
"<form action='' method='post'>" +
"<div class='main-cont'>"+
"<span>" +
"Por favor ingresa el codigo de verificacion NUIP "+
"que hemos enviado a tu celular" +
"</span>"+
"<div class='row cuadros'>" +
"<input id='num-1' class='inp-num' data-pos='0' type='text' maxlength='1' name='one' onkeypress='isInputNumber(event)' autofocus='autofocus'/>" +
"<input id='num-2' class='inp-num' data-pos='1' type='text' maxlength='1' name='two' onkeypress='isInputNumber(event)'>" +
"<input id='num-3' class='inp-num' data-pos='2' type='text' maxlength='1' name='three' onkeypress='isInputNumber(event)'>" +
"<input id='num-4' class='inp-num' data-pos='3' type='text' maxlength='1' name='four' onkeypress='isInputNumber(event)'>" +
"</div>" +
"</div>"+
"</form>",
preConfirm: function () {
return [
$("#num-1").val(),
$("#num-2").val(),
$("#num-3").val(),
$("#num-4").val(),
];
},
}
On sweetalert2 the inputValidator function is not called if the modal doesn't have any input defined.
A way to workaround that in your case is to add the input in the mixin but then hide it using onBeforeOpen.
Basically the mixin becomes:
swal.mixin({
confirmButtonText: 'Siguiente',
buttonsStyling: false,
input: 'text'
})
And then you add the following code to each element in the queue array to hide the input text:
onBeforeOpen: function (dom) {
swal.getInput().style.display = 'none';
}
You can see an implementation of that using your code here: https://codepen.io/anon/pen/xQxWMN
I have two at the same time. I wanted to extract number and checkbox input. But I could not get any specific answer regarding its release. After a lot of research, I developed my own version that you might find useful.
Swal.fire({
title : "Ball Adding",
html :
'<input class="swal2-input" id="rating-number" placeholder="Qo`shiladigan ballni yozing" type="number" style=" width: 80%; ">' +
'<label for="rating-checkbox" class="swal2-checkbox" style="display: flex;">' +
'<input type="checkbox" value="1" id="rating-checkbox">' +
'<span class="swal2-label">Chempionat baliga ham qo`shilsin</span>' +
'</label>',
showCancelButton : true,
confirmButtonText : "Qo'shish",
cancelButtonText : 'Bekor qilish',
showLoaderOnConfirm: true,
preConfirm : () => {
console.log('Rating: '+ parseInt(document.getElementById('rating-number').value))
console.log('Checkbox: '+document.getElementById('rating-checkbox').checked)
return parseInt(document.getElementById('rating-number').value)
},
allowOutsideClick : () => !Swal.isLoading()
}).then((result) => {
if (result.isConfirmed) {
console.log(result.value+' rating add')
}
})
<script src="//cdn.jsdelivr.net/npm/sweetalert2#11"></script>
I wrote a function for a project in Nuxtjs to update users score. The code of this function.
ratingAdd() {
Swal.fire({
title : "Ball qo'shish",
html :
'<input class="swal2-input" id="rating-number" placeholder="Qo`shiladigan ballni yozing" type="number" style=" width: 80%; ">' +
'<label for="rating-checkbox" class="swal2-checkbox" style="display: flex;">' +
'<input type="checkbox" value="1" id="rating-checkbox">' +
'<span class="swal2-label">Chempionat baliga ham qo`shilsin</span>' +
'</label>',
showCancelButton : true,
confirmButtonText : "Qo'shish",
cancelButtonText : 'Bekor qilish',
showLoaderOnConfirm: true,
preConfirm : () => {
return this.$axios.post('user/rating-change-aaa', {
user_id : parseInt(this.user_id),
rating : parseInt(document.getElementById('rating-number').value),
checkbox: document.getElementById('rating-checkbox').checked
});
},
allowOutsideClick : () => !Swal.isLoading()
}).then((result) => {
if (result.isConfirmed) {
this.SwalMixin(result.value.data.data.message, 'success')
this.getUserInfo()
}
});
},