rendering anchor href with json2html - javascript

I am trying to render an anchor with json2html with the following transform:
'renderTimeline':[ {
tag: "a",
class: "btn btn-warning btn-circle",
style: "float: right;",
html: "<i class=\"icon-remove\"></i>",
"href": function() {
var myhref = "javascript:delSchedule(" + this + ");";
return myhref;
}
}]
intention is to delete the json object,which is passed to it with :
$('#sunTimeLine').json2html(sched1.sunday, transforms.renderTimeline, {'events':true});
I get the following as o/p on the rendered html:
<a class="btn btn-warning btn-circle" style="float: right;" href="javascript:delSchedule([object Object]);"><i class="icon-remove"></i></a>
when i click on the link(button) i get a message in browser console:
SyntaxError: missing ] after element list
Please help me solve this issue.

Assuming you are trying to pass the reference of the clicked element to the delSchedule function, you need to change your href definition like this:
"href": function() {
var myhref = "javascript:delSchedule(this);"; // note 'this' is part of the string, not concatenated
return myhref;
}

{
tag: "a",
class: "btn btn-warning btn-circle",
style: "float: right;",
html: "<i class=\"icon-remove\"></i>",
"href": function() {
var myhref = "javascript:delSchedule(this);";
return myhref;
}
}

check the documentation for more examples but you should be using the built in jquery events like so
'renderTimeline':[ {
tag: "a",
class: "btn btn-warning btn-circle",
style: "float: right;",
html: "<i class=\"icon-remove\"></i>",
"onclick": function(e) {
delSchedule(this);
}}
}]
Note that json2html supports most jquery events by just adding the prefix "on" to the event .. eg onclick, onfocus, etc...

Following code solved my issue:
'renderTimeline':[ {
tag: "a",
class: "btn btn-warning btn-circle",
style: "float: right;",
html: "<i class=\"icon-remove\"></i>",
"onclick": function(e) {
delSchedule(e);
}}
}]
If I am passing the following json :
{ monday:[ { startTime:10:00, endTime: 12:00, room_id:cse124 }, { startTime:13:00, endTime: 15:00, room_id:lotus } ] }
I want to be able to access "monday" in the function delSchedule(). How do i do this? Please help.

Related

How to parse JSON data into HTML elemnets

I have a JSON data with HTML.
Like this:
"elements":[
{
"element":".dyno-text",
"value":"This fun here.<br> <button type='button' onclick='changeTheme(this)' data-theme='sketchy' class='theme-link btn btn-light'>Sketchy</button>",
"class": 'text-success'
}
]
How will I parse this JSON data to Bootstrap Layout Design for example: Button will come to real.
Thanks
Uses Vue.component to assembly JSON as one component may be one solution.
But you may need to adjust the HTML template in JSON. Because for supporting some features such as onclick, binding class, it will be one serious headache.
Below is one demo which may provide you some ideas how to reach your goal.
new Vue ({
el:'#app',
data () {
return {
"elements":[
{
"element":"dyno-text",
"value":"This fun here.<br> <button type='button' #click='changeTheme(this)' data-theme='sketchy' class='theme-link btn btn-light'>Sketchy</button>",
"class": 'text-success',
"methods": {
// changed onclick to #click, if you still like to use 'onclick' in the template, you have to define window.changeTheme
changeTheme: function(obj) {console.log('clicked')}
}
}
]
}
},
methods: {
createComponent(element) {
/*window.changeTheme = function () {
console.log('clicked by onclick')
}*/
return Vue.component(element.element, {
template: `<div ref="test">${element.value}</div>`,
mounted: function () {
this.$nextTick(() => {
this.$refs.test.querySelector('button.btn').classList.add(element.class)
// or adjust your template in JSON like `<button :class="classes"/>`, then binds element.class to data property=classes
})
},
methods: element.methods
})
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
<div id="app">
<div class="container">
<div v-for="(item, index) in elements" :key="index">
<component :is="createComponent(item)"/>
</div>
</div>
</div>
You can do something like this; I changed the element in order to create a known htmlElement, so what you do here is to iterate your array of elements and you insert them inside the body, set the value, and toggle the class.
--Edit--
Cleanner solution thanks to pointing it out supercool
Documentation of classList
let elements=[
{
"element":"div",
"value":"This fun here.<br> <button type='button' onclick='changeTheme(this)' data-theme='sketchy' class='theme-link btn btn-light'>Sketchy</button>",
"class": 'text-success'
}
]
elements.forEach((elemen,i)=>{
let createdElement= document.createElement(elemen.element)
createdElement.innerHTML = elemen.value
createdElement.classList.toggle(elemen.class)
document.body.appendChild(createdElement)
})

Dynamic datatable Jquery

I would like to know how could I make a data table row with Dynamic data.
I have this table:
But I want to show the red data dynamically according to my user roles.
For example if my role is equal to supervisor show him one buttons or if my role is different to this one show to user other buttons
this is my html table:
<div class="table-responsive-lg table-responsive-md">
<table id="table" class="table table-hover">
<thead>
<tr>
<th></th>
<th>Solicitante</th>
<th>Dia de solicitud</th>
<th>Estatus</th>
<th>Acciones</th>
</tr>
</thead>
</table>
</div>
And I call this method in document ready function
table = $('#table').DataTable({
'data': data
, 'columns': [
{
'className': 'details-control',
'orderable': false,
'data': null,
'defaultContent': ''
},
{ 'data': 'name' },
{ 'data': 'request.dateRquest' },
{ 'data': 'request.status' },
{
"className": '',
"orderable": false,
"data": null,
"defaultContent": '<button class= "btn btn-success btn-circle asignar" title="Asignar"> <i class="material-icons">assignment_ind</i></button>'+
" "+
'<button class= "btn btn-danger btn-circle rechazar" title="Rechazar"> <i class="material-icons">close</i></button>'
}
],
'order': [[1, 'asc']]
})
Can I iterate the data that i want to put on my table? In the picture I have a column call estatus if the estatus is different to pending I want to make other action with the button.
So I need to check the role of person that is sign in and check the status of each row
I want to make someting like this:
If(role == xRole && data.status != 'Pending'){
Change style of button
Put a different class for example change .Assign to .CloseRequest
}
If I knew how to interactue with the data that I'm going to put in the rows before the table was maked it will be more easy
It is possible?
Change
"defaultContent": '<button class= "btn btn-success btn-circle asignar" title="Asignar"> <i class="material-icons">assignment_ind</i></button>'+
" "+
'<button class= "btn btn-danger btn-circle rechazar" title="Rechazar"> <i class="material-icons">close</i></button>'
to
"defaultContent": getButtons()
and define this function:
function getButtons() {
switch (role) {
case "admin": return "sometemplate1";
default: return "sometemplate2";
}
}
just make sure that role is properly defined.

why Button onclick didnt work on datatables serverside ? Laravel 6

I have function delete on my table ( using datatables) this delete is work normally but i want to add some pop up alert like "onclick" on my delete , but its didnt work on my button
public function indexDataTables_pns()
{
$pns = Data_pns::with('users','master_golongan','master_jabatan')->get();
return Datatables::of($pns)->addIndexColumn()
->addColumn('Nama', function ($pns) {
return ''.$pns->users->nama.'';
})
->editColumn('edit', function ($pns) {
return '<i class="glyphicon glyphicon-edit"></i>';
})
->editColumn('hapus', function ($pns) {
$c = csrf_field();
$m = method_field('DELETE');
return "<form action='/delete/$pns->id' method='POST')>
$c
$m
<button style='margin-left:10px; width: 30px;' type='submit'
class='btn btn-xs btn-danger delete' onclick='return
confirm('do you want to delete this data ?')'>
<i class='glyphicon glyphicon-remove-circle'></i>
</button>
</form>";
})
->rawColumns(['Nama' => 'Nama','hapus' => 'hapus','action' => 'action','edit'=>'edit'])
->make(true);
}
its didnt work
i trying adding class
<form action='/delete/$pns->id' method='POST' class='delete-form'>
and add this script
<script>
$('.delete-form').submit(function(event){
if(!confirm('Anda yakin mau menghapus item ini ?')){
event.preventDefault();
}
});
but still didnt work . i put this on under my view .
i try to add onsubmit like this
<form onsubmit='return confirm('Anda yakin mau menghapus item ini ?')'>
still didnt work , iam from this thread this link , but i didnt find the answer ..
look this image
can someone help me ?
UPDATE
i tryng add this form class
return "<form action='/delete/$pns->id' method='POST' class='delete-form')>
this pop up is showing after i click this delete button but this message is null/empty ,
#push('scripts')
<script>
$(function() {
$('#table').DataTable({
processing: true,
serverSide: true,
responsive: true,
ajax: '{!! route('d_pns') !!}',
columns: [
{ data: 'DT_RowIndex', name: 'DT_RowIndex', orderable: false,searchable: false},
{ data: 'Nama', name: 'Nama'},
{ data: 'NIP_lama', name: 'NIP_lama'},
{ data: 'NIP_baru', name: 'NIP_baru'},
{ data: 'TMT_CPNS', name: 'TMT_CPNS'},
{ data: 'TMT_PNS', name: 'TMT_PNS'},
{ data: 'TMT_gol_ruang', name: 'TMT_gol_ruang'},
{ data: 'master_golongan.golongan', name: 'master_golongan.golongan'},
{ data: 'master_jabatan.nama_jabatan', name: 'master_jabatan.nama_jabatan'},
{ data: 'edit', name: 'edit', orderable: false, searchable: false},
{ data: 'hapus', name: 'hapus', orderable: false, searchable: false},
],
});
})
$('.delete-form').submit(function(event){
if(!confirm('Anda yakin mau menghapus item ini ?')){
event.preventDefault();
}
});
</script>
#endpush
why this message on confirm is empty ?
Your 1st attempt issue looks to be escaping the quotes " and '. try putting your message inside double quotes " ". This should resolve your problem
<button style='margin-left:10px; width: 30px;' type='submit'
class='btn btn-xs btn-danger delete' onclick='return
confirm("do you want to delete this data ?")'>
<i class='glyphicon glyphicon-remove-circle'></i>
</button>
SOLVED
Need to add
<script type="text/javascript">
function confirm_delete() {
return confirm('Apakah anda yakin untuk menghapus data ini ? ');
}
</script>
and add onclick return confirm_delete()
I will be dropping this for anyone that need to know how to use onclick from laravel yajra serverside.
$datatable = datatables()->collection($data)
->addColumn('action', function($data){
$button = '
<button type="button" data-security="'.$data->security.'" class="btn btn-warning btn-sm" onclick="OrderTicket(\''.$data->security.'\')">Sell
</button>
<button type="button" data-security="'.$data->security.'" class="btn btn-info btn-sm" onclick="createRequest(\''.$data->security.'\')">Buy
</button>
';
return $button;
})
->rawColumns(['action'])
->addIndexColumn()
->make(true);
return $datatable;
All you have to do is to escape the strings onclick="OrderTicket(\''.$data->security.'\')"

How to apply button().trigger() outside DOM on angular datatables (l-lin) in AngularJS

I have created a table like below with dtInstance:
<table datatable="ng" dt-options="dtOptions" dt-column-defs="dtColumns" dt-instance="dtInstance" class="row-border hover">
</table>
In controller I defined dtOptions and dtColumns:
$scope.dtInstance = {};
$scope.dtOptions = DTOptionsBuilder.newOptions()
.withDOM('frtip')
.withButtons([
{
extend: "excelHtml5",
className: 'btn btn-success buttons-excel',
filename: "List",
title: "List",
text: "Export",
exportOptions: {
columns: ':visible'
},
//CharSet: "utf8",
exportData: { decodeEntities: true }
}
My question is I want to create a button outside the dt table and trigger the .withButtons export button when ng-click
I would also like to hide the .withButtons generated inside the table.
Got this error
TypeError: Cannot read property 'button' of undefined
when I use below code
<button ng-click="dtInstance.DataTable.button('.buttons-excel').trigger()">Download EXCEL</button>
Thanks
Try with initializing dtInstance variable with null instead of {}:
$scope.dtInstance = null;
Keep everything else same.
Update:
Check if you've imported all the plugins required. Follow below example I've created to make sure:
Plunker example

Why are my icons not showing up?

This is a zip to the full project QuickLinks.v4
I have been collaborating on a project and we are stuck on an issue, we want all of the icon to have a right click menu that has several options that are unique to each icon. We are almost done but now the icons are not being drawn to the screen. We are only working on the first 5 at the time. This is my first time working with jQuery and I would appreciate any help.
I will now post pieces of the project that I think are relevant.
icon.html
<a target="_blank">
<img class="icons" />
<div class="data">
<div>
<input type="hidden" class="login" />
<input type="hidden" class="username" />
<input type="hidden" class="password" />
</div>
</div>
</a>
icon.js
function buildIcons() {
var icons = [
["https://discordapp.com/", "discord-icon", "icons/discord.png", "social", "Discord",
[
["Main Account", "lela_null", "somepass"],
["Bot Account", "Uta Yuki", "somepass"]
]
],
["https://www.youtube.com/", "youtube-icon", "icons/youtube.png", "social", "YouTube",
[
["Main Account", "lela#email", "somepass"],
]
],
["https://www.facebook.com/?sk=h_chr", "facebook-icon", "icons/facebook.png", "social", "Facebook",
[
["Main Account", "lela#email", "somepass"],
]
],
["https://www.twitter.com/", "twitter-icon", "icons/twitter.png", "social", "Twitter",
[
["Main Account", "lela#email", "somepass"],
]
],
["https://mg.mail.yahoo.com/neo/launch?.rand=8647i3s40jpvp", "ymail-icon", "icons/ymail.png", "social", "Yahoo Mail",
[
["Main Account", "lela#email", "somepass"],
]
]
];
$.get('data/icon.html', function(data) {
var icon;
icons.forEach(function(iconData, index, array) {
console.log(index);
icon = $(data).insertAfter("#" + iconData[3]);
$(icon).find("img").attr("src", iconData[2]);
});
});
};
script.js
/* get icon id */
function buildMenu(iconId) {
$("#remove").click(function() {
$("#" + iconId).hide();
cancel();
});
$("#menu-title").text($("#"+iconId).data("name"));
$("#site-link").attr("href", $("#" + iconId).parent().attr("href")).click(cancel);
switch(iconId) {
};
}
/* set right click for icons */
$(document).ready(function() {
buildIcons();
$(".icons").on("contextmenu", function(e) {
buildMenu(this.id);
$("#contextmenu").show().css({
top: e.clientY,
left: e.clientX
});
e.preventDefault();
});
});
function cancel() {
$("#contextmenu").hide();
}
There is more files and code, if you may need, you may download it above.
Also the console says TypeError: a is null in my jQuery.js file.
Check this
$.get('data/icon.html', function(data) {
icons.forEach(function(iconData, index, array) {
console.log(index);
// Get 'data' as jQuery object
var $data = $(data);
// Find image tag and set source
$data.find('img').attr('src', iconData[2]);
//Finally put it on page
$data.insertAfter("#" + iconData[3]);
});
});
jQuery does not have the ability to include html from another file.

Categories

Resources