Align Text in Javascript append data - javascript

I will really appreciated any help. I am trying to fix the display of the text in my html. I use javascript and call the variable and display in html. However the display of the text is not what i desired.
JAVASCRIPT
$(document).ready(function(){
var table= $('#data-table').DataTable({
"ajax" : "employee_data.json",
"columns" : [
{ "data" : "name" },
{ "data" : "gender"},
{ "data" : "designation"},
{ "data" : "image"},
{"defaultContent": '<div style="text-align:center"><button style="width:100%; margin-top: 5px;" class="btn btn-danger" > support </button></div>'}
]
});
$('#data-table tbody').on( 'click', 'button', function () {
var data = table.row( $(this).parents('tr') ).data();
alert( "You Click" + " "+data['name'] );
$new="You Click" + " "+data['name'] ;
$images=data['image'];
$names=document.getElementById("name").append = data['name'];
$gender=document.getElementById("gender").append = data['gender'];
$('#img-container').append(data['image']+" " + $names+$gender+" </p>"+"<br>" );
} );
});
Running Result:
Desired Output:

Try to change your style using this unit of measurement to make it responsive to the sizing.
$(document).ready(function() {
var table= $('#data-table').DataTable( {
"ajax" : "employee_data.json",
"columns" : [
{ "data" : "name" },
{ "data" : "gender"},
{ "data" : "designation"},
{ "data" : "image"},
{"defaultContent": '<div style="font-size:15vw;"><button style="width:100%; margin-top: 5px;" class="btn btn-danger"> support </button></div>'}
]
});

Related

How am I able to get the column of the data in the DataTable where my button is at in ajax?

Hello I am fairly new to datatable and I would like to seek help in retrieving the User ID when I click the button and that would trigger another ajax call where it will do a POST method but I am unsure how it can be done within the script tag. Is this the right method to implement the data and the button? I really need some advice on this.
Here is my code :
<script>
uId = sessionStorage.getItem('uId')
username = sessionStorage.getItem('username')
var userListTable = $('#userListTable').dataTable({
'ajax': {
"type" : "GET",
"url" : "http://localhost:8080/Test-war/webresources/users/" + uId + "/retrieveUserList",
"dataSrc": ""
},
'columns': [
{title : "User ID", "data" : "id"},
{title : "Username", "data" : "username"},
{title : "Gender", "data" : "gender"},
{title : "Email", "data" : "email"},
{title : "Contact", "data" : "contact"},
{title : "Created", "data" : "created", "render" : function(data) {
var date = new Date(data);
var month = date.getMonth() + 1;
return (month.toString().length > 1 ? month : "0"
+ month) + "/" + date.getDate() + "/" + date.getFullYear();
}},
{title : "Follow User", "defaultContent" : '<button onclick="followUser()">Follow User</button>'},
{title : "Unfollow User", "defaultContent" : '<button onclick="unfollowUser()">Unfollow User</button>'},
]
});
</script>
From here I am using a function followerUser() but I have no idea how am I able to get the tId of the row that the button was clicked at.
function followUser() {
var tId =
$.ajax({
type: "POST",
url: "http://localhost:8080/Test-war/webresources/users/" + tId + "/followUser",
data: body,
contentType: "application/json; charset=utf-8",
success: function(data, textStatus, xhr)
{
alert("You have successful followed user")
window.location.href = "viewUserList.html";
console.log(data)
console.log(textStatus)
},
error: function(xhr, error, errorType) {
alert("Error following user...")
}
});
Here is the image of the datatable :
You can use something like below code. you can use datatable API to fetch row data.
var dataSet = [
{'engine':'Webkit','browser':'Safari 1.2','platform':'OSX.3','version':'125.5','grade':'A'},
{'engine':'Other browsers','browser':'All others','platform':'-','version':'-','grade':'U'}
];
$(document).ready(function() {
$('#demo').html('<table class="display" id="example"></table>');
$('#example').dataTable( {
"data": dataSet,
"columns": [
{ "sortable" : false, "data": null, "defaultContent": "<button>Select</button>", "title" : "Choose"
},
{ "title": "Engine", "data": "engine" },
{ "title": "Browser", "data": "browser" },
{ "title": "Platform", "data": "platform" },
{ "title": "Version", "data": "version", "class": "center" },
{ "title": "Grade", "data": "grade", "class": "center" },
{ "defaultContent": true, "data": "existing", "visible": false }
],
initComplete: function(oSettings, json) {
console.log('drawing complete');
if (oSettings.fnRecordsTotal() > 1) {
$('#example').DataTable().row.add({
'engine' : 'Presto',
'browser' : 'Opera 7.5',
'platform' : 'Win 95+ / OSX.2+',
'version' : '-',
'grade' : 'A',
'existing' : false
}).draw();
}
}
} );
$('#example tbody').on('click', 'button', function(e) {
var data = $('#example')
.DataTable()
.row( $(this).parents('tr') )
.data();
console.log(data.version);// obj.columnname you can use data.id in you case to fetch User id
});
});
here is working example

Add link to Ajax sourced data in jQuery Datatables

I want to add a link/href to the 2nd column (the one with "C" data in it). I have tried the columns render function but it only has data of the current column.
https://datatables.net/reference/option/columns.render
I want to use data from different columns onto anchor tag of column 2
this guy here
https://stackoverflow.com/a/47696609/11575565
explains using rowID which would've solved my problem but this isnt working.
I tried using $.getJSON and append() over ajax function but it doesnt work as well.
$(document).ready(function() {
var table = $('#bla').DataTable({
"ajax" : "blist.json",
"columns" : [
{ "data" : null,defaultContent: "-" },
{ "data" : "C" },
{ "data" : "B" },
{ "data" : "D" },
{ "data" : null,defaultContent: "-" },
{ "data" : null,defaultContent: "-" },
],
[the array in blist.json has data "A","B","C","D","E"]
Say, your Link value is in key E then, you would be able to use render as shown below.
"columns" : [
{ "data" : null,defaultContent: "-" },
{ "data" : "C",
"render": function(data, type, row, meta){
if(type === 'display'){
data = '' + data + '';
}
return data;
}
},
{ "data" : "B" },
{ "data" : "D" },
{ "data" : null,defaultContent: "-" },
{ "data" : null,defaultContent: "-" },
]

Conditional checking of "datatable checkboxes" in jQuery

Hi I'm trying to create a table that consists of checkboxes. And each row has its own class and ID.
$('#niisPrprtyCoverageTable').dataTable({
"data" : coverageList,
"columns" : [ {
"data" : "seqNo",
"visible" : false
}, {
"data" : "coverageCode"
}, {
"data" : "coverageName"
}, {
"data" : "coverageCode",
"width" : "80px",
"className" : "text-center",
render : function(data, type, row) {
var arrData = data.split(";");
var coverageCd = arrData[0];
var coverageRel = nvl(arrData[1], coverageCd);
data = '<input class="'+coverageRel+'" id="'+coverageCd+'" type="checkbox" onClick="addToArray('
+ coverageCd
+ ','
+ coverageRel
+ ')">';
return data;
}
} ],
"searching" : false,
"bLengthChange" : false,
"iDisplayLength" : 15 ,
"bSort" : false,
"columnDefs" : [ {
"targets" : [ 1, 2 ],
"className" : "left"
}, {
"targets" : [ 2 ],
"width" : "150px",
}, {
"targets" : [ 1 ],
"width" : "100px",
}, {
"targets" : [ 3 ],
"width" : "50px",
"className" : "text-center"
} ]
});
niisPrptyCoverageTable = $('#niisPrprtyCoverageTable').DataTable();
$('#select-all').on('click', function(){
alert('ss');
// Get all rows with search applied
var rows = niisPrptyCoverageTable.rows({ 'search': 'applied' }).nodes();
// Check/uncheck checkboxes for all rows in the table
$('input[type="checkbox"]', rows).prop('checked', this.checked);
});
What should happen is, if I check the main row, all the rows under his 'code or id' should be checked also.
It works but only on the first page
but doesn't work on the second page of the datatable
var array = [];
function addToArray(coverageCd, coverageRel) {
var rows = niisPrptyCoverageTable.rows('.'+coverageRel).nodes().className;
$('input[class='+coverageCd+']', rows).prop('checked', '#'+coverageCd.checked);
}
Use $() API method to get access to elements on all pages, not just current page.
For example:
var array = [];
function addToArray(coverageCd, coverageRel) {
var rows = niisPrptyCoverageTable.rows('.'+coverageRel).nodes().className;
niisPrptyCoverageTable.$('input[class='+coverageCd+']', rows).prop('checked', '#'+coverageCd.checked);
}
Alternatively see jQuery DataTables Checkboxes extension for easier handling of checkboxes in a table powered by jQuery DataTables.

datatables not binding Json with columns

Here is my code
oTable = $('#userlisttable')
.dataTable(
{
"serverSide" : false,
"ajax" : {
"url" : context + "user/get",
},
"columns" : [ {
"data" : "username"
}, {
"data" : "userpassword"
}, {
"data" : "usertype"
}, {
"data" : "firstname"
}, {
"data" : "lastname"
}, {
"data" : "emailaddress"
}, {
"data" : "isactive"
}, ],
"columnDefs" : [ {
"targets" : "7",
"data" : "userId",
"render" : function(data, type,
full, meta) {
return '<a href="#" id="row'
+ data
+ '" class="btn btn-success" onclick="callModal(id)"><i class="glyphicon glyphicon-edit icon-white"></i>EDIT</a> <a href="#" id="row'
+ data
+ '" class="btn btn-danger" onclick="callDeleteModal(id)"><i class="glyphicon glyphicon-trash icon-white"></i>Deactivate</a>';
}
} ],
"sDom" : 'T<"clear">lfrtip',
"oTableTools" : {
"sRowSelect" : "single",
"sSwfPath" : "../../resources/swf/copy_csv_xls_pdf.swf",
"aButtons": [
"csv"
]
}
});
server returns following Json
[{"password":"password","username":"user","lastAccess":1408089626000,"creationDate":1408089626000,"userId":1,"lastName":"reddy","isActive":"y","firstName":"manjari","email":"man#gmail.com","isLdap":"y","ldapQuery":"query","accessType":"any","usertype":"admin"}]
but data is not dislpled in datatable.
From the doc on the ajax option (scroll down to the examples) :
Get JSON data from a file via Ajax, using dataSrc to read data from a plain array rather than an array in an object:
$('#example').dataTable( {
"ajax": {
"url": "data.json",
"dataSrc": ""
}
} );

How can I get JSON data without an array as the key?

I'm trying to get JSON data to turn it into html but the JSON code I have access to does not show an array to use as the data key.
Does anyone know how I can go about getting this data? My data values are coming up "undefined" in the HTML.
Sample data:
[ { "stuff" : {
"categories" : null,
"value-1" : "a string of cool text to display",
"value-2" : 3,
"value-3" : null,
"value-4" : [ ],
"value-5" : 58505,
"value-6" : true,
"value-7" : false,
} },
{ "stuff" : {
"categories" : null,
"value-one" : "another string of cool text to display",
"value-two" : 3,
"value-three" : null,
"value-four" : [ ],
"value-five" : 58505,
"value-six" : true,
"value-seven" : false,
} }
]
Sample code:
$(function() {
$.getJSON( "sample.json", function(data) {
$.each(data, function() {
$('<div></div>')
.hide()
.append('<p>' + this.value-one + '</p>')
.appendTo('#awesome')
.fadeIn();
});
});
});
Try:
$.each(data, function(key, value) {
$('<div></div>')
.hide()
.append('<p>' + value.stuff['value-one'] + '</p>')
.appendTo('#awesome')
.fadeIn();
});
Update: When object key has - in it, you can't access it with object.value-one, you must do object['value-one'].
You are not using jquery each correctly.
$.each(data, function(index, value) {
$('<div></div>')
.hide()
.append('<p>' + value.stuff['value-one'] + '</p>')
.appendTo('#awesome')
.fadeIn();
});

Categories