I have been studying and working endlessly with DataTables the past 2 weeks and gotten to a brick wall now. The issue I am trying to sort out is how I can pass values in a particular row when the button for that row is clicked on. As at now with my limited knowledge on DataTables and JQuery, when I have like 2 to 3 buttons in different rows and I click on each one, the value they all return back is the values in the first row only. Not sure how best I can solve this or where my error might lie. Any guide or help would be much appreciated. Thanks
<script type="text/javascript" charset="utf-8">
<!-- ------------------- Extract all Alerts ---------------------- -->
$(document).ready(function (){
var alertTable = $('#alert-table').DataTable({
"jQueryUI": true,
"columns": [
{ "data": "source", "visible": false },
{ "data": "host" },
{ "data": "description" },
{ "data": "priority" },
{ "data": "acknowledged", render: function( data, type, row ) {
if (data == "0" && row.priority > "2") {return '<div><form method="post" id="'+row.source + row.eventid+'" action="include/db_conn.php"> <input type="hidden" id="evtid" value ="'+row.eventid+'"> <input type="hidden" name="source" value ="'+row.source+'"> <INPUT TYPE="text" name="username" size="3" maxlength="3"> <input type="submit" name="'+row.source + row.eventid+'" onClick="ackbutton(this)" value="Ack Alert"></form></div>';
} return data;
}
}
],
});
setInterval (function(){
$.getJSON("data/json_data.txt", function (pcheckdata){
alertTable.clear().draw();
alertTable.rows.add(pcheckdata.alert).draw();
alertTable.columns.adjust().draw();
});
}, 10000);
});
function ackbutton() {
//e.preventDefault();
var $this = $(this);
var getvalues = $('#evtid').val();
alert(getvalues);
}
</script>
HTML:
<body>
<div class="all_tables">
<table id="alert-table" class="display" cellspacing="0">
<thead class="t-headers">
<tr>
<th>Server</th>
<th>Host</th>
<th>Description</th>
<th>Priority</th>
<th>Acknowledged</th>
<th>Eventid</th>
</tr>
</thead>
</table>
</div>
</body>
JSON
{
"alert": [
{
"source": "Server1",
"host": "host1",
"description": "Engine Alive",
"priority": "4",
"triggerid": "14531",
"acknowledged": "0",
"eventid": "3419709",
"value": "1"
},
{
"source": "Server2",
"host": "host2",
"description": "webapp down",
"priority": "2",
"triggerid": "18027",
"acknowledged": "1",
"eventid": "4012210",
"value": "1"
}
],
"error": []
}
You need to find the input with id 'evtid' in closest div of currently clicked ack button.
Example:
$(document).on('click','.submitButton',function(e){
e.preventDefault();
debugger
var $this = $(this);
var curEventId = $this.closest('div').find('#evtid');
var getvalues = curEventId.val();
alert(getvalues);
return false;
});
You can also use closest form instead of div.
var curEventId = $this.closest('form').find('#evtid');
Related
So I am using an array to populate a dropdown menu and right now that part works great. I use the value to help calculate service cost and i use the label to display the option name to the user. My issue now is that my form is sending the value(which is just the price) and not the label. I may need it to do both potentially if my paypal button is my submit button? im not sure. Right now i just have the form sending to discord though.
HTML for particular selection menu
<fieldset>
<label for="rank-tourn">
Select Tournament Title
</label>
<select id="rank-tourn" name="Desired Tournament Rank" class="menus form-select" onchange="onChangeCurrent()">
<option value="0" label="" >Select</option>
</select>
</fieldset>
java for populating list
function buildOptList(select, id) {
select.innerHTML = null;
//alert("Populate list");
for (var i = id; i < Rankings.length; i++) {
if ((id == 0) && (i == Rankings.length)) {
// do nothing
} else {
var el = document.createElement("option");
el.textContent = Rankings[i].label;
el.value = Rankings[i].value;
select.appendChild(el);
}
}
}
My array
var Rankings = [{
"id": 1,
"value": 10,
"label": "Bronze Title",
}, {
"id": 2,
"value": 10,
"label": "Silver Title",
}, {
"id": 3,
"value": 15,
"label": "Gold Title",
}, {
"id": 4,
"value": 20,
"label": "Platinum Title",
}, {
"id": 5,
"value": 25,
"label": "Diamond Title",
}, {
"id": 6,
"value": 30,
"label": "Champion Title",
}, {
"id": 7,
"value": 40,
"label": "Grand Champion Title",
}, {
"id": 8,
"value": 80,
"label": "Supersonic Legend Title",
}];
I have also tried using jquery to try and copy the selection label to a hidden field but im having trouble with that too.
This was my attempted jquery:
HTML
<input type='hidden' id='hidden' value='0' label=''/>
JQUERY
$("#rank-tourn").change(function () {
$("#hidden").text($(this).text());
alert($(this).text())
})
currently this alerts on change everysingle label together. I have tried adding the :selected to rank-tourn and then it fails to alert.
https://jsfiddle.net/Popo74123/q92jh1p0/465/ this is my code if its easier.
this.text() will get the value of everything, you need to find the pseudo selector :selected to display the one that was chosen
$("#rank-tourn").change(function () {
$("#hidden").text($(this).find(':selected').text());
alert($(this).find(':selected').text())
})
Just remove this line:
el.value = Rankings[i].value;
when an option doesn't have an explicit value, it's text becomes the value.
I have a simple datatable that shows some JSON data, received from an API endpoint.
I added a column that will hold a button on each row of the table. This button, when hit, will fire an AJAX request with the value of id for that specific row.
This actual code works, but now, instead of only sending the value of id, i would also like to edit the table so that, when the button is hit, it will send the values of id and item for that row. Can someone give me some piece of advice on how to do that?
On another question, i've been told to use Data Attributes, but i don't really know how would i integrate this into my current code. Any advice is appreciated.
$(document).ready(function() {
$(document).on('click', '.btnClick', function() {
var statusVal = $(this).data("status");
console.log(statusVal)
callAJAX("/request_handler", {
"X-CSRFToken": getCookie("csrftoken")
}, parameters = {
'orderid': statusVal
}, 'post', function(data) {
console.log(data)
}, null, null);
return false;
});
let orderstable = $('#mytalbe').DataTable({
"ajax": "/myview",
"dataType": 'json',
"dataSrc": '',
"columns": [{
"data": "item"
}, {
"data": "price"
}, {
"data": "id"
},],
"columnDefs": [{
"targets": [2],
"searchable": false,
"orderable": false,
"render": function(data, type, full) {
return '<button type="button" class="btnClick sellbtn" data-status="replace">Submit</button>'.replace("replace", data);
}
}]
});
});
You could use the full parameter of the DataTables render function to store the values of the current seleceted row. In this way:
return '<button type="button" class="btnClick sellbtn" data-status="' + btoa(JSON.stringify(full)) + '">Submit</button>';
In the above code, the data-status data attribute will contains the stringified version of the current object value in base64 by using btoa(). In base64 because for some reason we cannot directly store the stringified version of the object in the button's data attribute.
Then, in the button's click event, you have to do:
Decode the stringified object by using atob().
Parse into object by using JSON.parse().
Something like this:
$(document).on('click', '.btnClick', function() {
var statusVal = $(this).data("status");
// Decode the stringified object.
statusVal = atob(statusVal);
// Parse into object.
statusVal = JSON.parse(statusVal);
// This object contains the data of the selected row through the button.
console.log(statusVal);
return false;
});
Then, when you click in the button you will see this:
So, now you can use this object to send in your callAJAX() function.
See in this example:
$(function() {
$(document).on('click', '.btnClick', function() {
var statusVal = $(this).data("status");
// Decode the stringified object.
statusVal = atob(statusVal);
// Parse into object.
statusVal = JSON.parse(statusVal);
// This object contains the data of the selected row through the button.
console.log(statusVal);
return false;
});
let dataSet = [{
"id": 1,
"item": "Item 1",
"price": 223.22
},
{
"id": 2,
"item": "Item 2",
"price": 243.22
},
{
"id": 3,
"item": "Item 3",
"price": 143.43
},
];
let orderstable = $('#myTable').DataTable({
"data": dataSet,
"columns": [{
"data": "item"
}, {
"data": "price"
}, {
"data": "id"
}, ],
"columnDefs": [{
"targets": [2],
"searchable": false,
"orderable": false,
"render": function(data, type, full) {
// Encode the stringified object into base64.
return '<button type="button" class="btnClick sellbtn" data-status="' + btoa(JSON.stringify(full)) + '">Submit</button>';
}
}]
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="//cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
<link href="//cdn.datatables.net/1.10.20/css/jquery.dataTables.min.css" rel="stylesheet" />
<table id="myTable" class="display" width="100%"></table>
Hope this helps!
I have an input type check box and load from database and form like this
<input type="checkbox" name="akses[]"
id="<?php echo $menu_id;?>"
value="<?php echo $action_name;?>"> <?php echo $menu_name;?>
and my json is
{
"status": 200,
"message": "sukses",
"data": {
"fullname": "TEST",
"username": "TEST_USER",
"position": "24",
"privileges_status": "based on jabatan",
"list_menu": [{
"action_name": "menu1 ",
"parent_id": 9,
"menu_id": 15,
"menu_name": "Menu 1"
}, {
"action_name": "menu2",
"parent_id": 9,
"menu_id": 16,
"menu_name": "Menu 2"
}]
}
}
I'm already successfully parsing the id using ajax, but the problem is that I don't know how to to check when id from json is same like the id in input.
If I define manually like
<input type="checkbox" name="akses[]" id="15" value=""> Menu 1
I can check and automatically check the checkbox
Now I change my input type like this
<input type="checkbox" name="akses[]" id="menu1" value=""> Menu 1
UPDATE: The js like this after implementing suggested answer
for (var i = 0; i < res['data']['list_menu'].length; i++)
{
var action_name = res['data']['list_menu'][i]['action_name'];
var idsFromJSON = new Array();
idsFromJSON.push(action_name);
console.log(idsFromJSON);
$("[name='akses[]']").each(function() {
this.checked=idsFromJSON.indexOf(this.id)!=-1;
});
}
but didn't work. if I declare array manually like this it works
var idsFromJSON=["menu1", "menu2"];
You want something like this
I would however recommend not to have numeric IDs
var idsFromJSON=["menu15","menu16"];
$("[name='akses[]']").each(function() {
this.checked=idsFromJSON.indexOf(this.id)!=-1;
});
im trying to import a json url to html in a table. The problem is when i get the data i get 25 rows i get this on the web console: Object { data: Array[25], paging: Object } I also have the following code which is designed for only one row i guess .And i understand i have Loop over each object, appending a table row with the relevant data of each iteration. The problem is i don´t how to do it, i´m not an expert . Thank you for your help!
This is the data i get on the json url :
{
"data": [
{
"created_time": "2017-11-10T01:24:47+0000",
"permalink_url": "https://www.facebook.com/DBZSFANSOFICIAL2/posts/1539014319521507",
"id": "949007375188874_1539014319521507"
},
{
"created_time": "2017-11-10T01:23:37+0000",
"permalink_url": "https://www.facebook.com/DBZSFANSOFICIAL2/posts/1539013649521574",
"id": "949007375188874_1539013649521574"
},
{
"created_time": "2017-11-09T23:59:15+0000",
"permalink_url": "https://www.facebook.com/DBZSFANSOFICIAL2/posts/1538951229527816",
"id": "949007375188874_1538951229527816",
"shares": {
"count": 20
}
},
{
"created_time": "2017-11-09T23:32:30+0000",
"permalink_url": "https://www.facebook.com/DBZSFANSOFICIAL2/posts/1538935439529395",
"id": "949007375188874_1538935439529395"
},
And this my code
<body>
<input type="text" class="txtPagina">
<button class="btnBuscar">Buscar</button>
<table class="tabla" border='1'>
<tr>
<td>created time</td>
<td>permalink url</td>
<td>id</td>
<td>Shares Count</td>
</tr>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('.btnBuscar').on('click', function (){
var pagina = $('.txtPagina').val();
//Ajax
$.ajax({
type: "GET",
dataType: "json",
url: "https://graph.facebook.com/"+pagina+"/feed?fields=created_time,permalink_url,id,shares& access_token=mytoken",
success: function(data){
console.log(data);
$('.tabla').append("<tr><td>"+data.created_time+"</td><td>"+data.permalink_url+"</td><td>"+data.id+"</td><td>"+data.shares+"</td></tr>");
},
error: function (){
console.log("Error");
}
});
});
});
</script>
</body>
</html>
success: function(data){
console.log(data);
$('.tabla').append("<tr><td>"+data.created_time+"</td><td>"+data.permalink_url+"</td><td>"+data.id+"</td><td>"+data.shares+"</td></tr>");
},
should be
success: function(data){
$.each(data.data, function(i, d){
var s = d.shares ? '<td>'+d.shares.count+'</td>' : '';
$('.tabla').append('<tr><td>'+d.created_time+'</td><td>'+d.permalink_url+'</td><td>'+d.id+'</td>'+s+'</tr>');
});
},
function create(t,attr,parent_node,innerdata){
var dom = document.createElement(t)
for(key in attr){
dom.setAttribute(key,attr[key])
}
dom.innerHTML = innerdata;
parent_node.appendChild(dom)
return dom;
}
window.onload = function () {
var d = {
"data": [
{
"created_time": "2017-11-10T01:24:47+0000",
"permalink_url": "https://www.facebook.com/DBZSFANSOFICIAL2/posts/1539014319521507",
"id": "949007375188874_1539014319521507"
},
{
"created_time": "2017-11-10T01:23:37+0000",
"permalink_url": "https://www.facebook.com/DBZSFANSOFICIAL2/posts/1539013649521574",
"id": "949007375188874_1539013649521574"
},
{
"created_time": "2017-11-09T23:59:15+0000",
"permalink_url": "https://www.facebook.com/DBZSFANSOFICIAL2/posts/1538951229527816",
"id": "949007375188874_1538951229527816",
"shares": {
"count": 20
}
},
{
"created_time": "2017-11-09T23:32:30+0000",
"permalink_url": "https://www.facebook.com/DBZSFANSOFICIAL2/posts/1538935439529395",
"id": "949007375188874_1538935439529395"
},
]
}
var tb= document.getElementById('inputTable')
f = {"created_time":1,"permalink_url":1,"id":1,"shares":1}
d['data'].forEach(function(val){
tr_dom = create('tr',{},tb,'')
Object.keys(f).forEach(function(tr){
if(tr in val){
if('shares' == tr)
td_dom = create('td',{},tr_dom,val[tr]['count'])
else
td_dom = create('td',{},tr_dom,val[tr])
}else
td_dom = create('td',{},tr_dom,'')
})
})
};
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<table border='1'>
<thead>
<th>Create Time</th>
<th>permalink_url</th>
<th>id</th>
<th>Share</th>
</thead>
<tbody id="inputTable">
</tbody>
</table>
</body>
</html>
I would like to output a bootstrap label for one value of a field in a JQuery dataTable. The fields possible values can be '0' or '1' and depending on this result I want to decide which bootstrap label I want to output in the dataTable. I wonder how I can realize the if statement depending on the result of the field "enabled" and how I can fill the field with my html code:
My JQuery:
$(document).ready(function() {
$('#accountOverview').dataTable( {
"ajax": {
"url": "/database/accounts.php",
"data": {"action": "selectAccounts"},
"dataSrc": ""
},
"columns": [
{ "data": "email" },
{ "data": "platform" },
{ "data": "coins" },
{ "data": "profitDay" },
{ "data": "playerName" },
{ "data": "tradepileCards" },
{ "data": "tradepileValue" },
{ "data": "enabled" }
],
"autoWidth": false
});
});
I need to use something like this for the result of the "enabled" field:
if(enabled==1) <label class="label label-success">Online</label>
else <label class="label label-error">Offline</label>
You can add a class to your <td class="enabled>
DUMMY HTML CODE:
<table>
<thead><tr><th>i</th></tr></thead>
<tbody><tr><td class="enabled">0</td></tr>
<tr><td class="enabled">1</td></tr>
</tbody>
</table>
and add manipulate via javascript:
var a = document.getElementsByClassName('enabled');
for (var i = 0; i<a.length;i++) {
if (a[i].textContent == 1) {
a[i].innerHTML = '<label class="label label-success">Online</label>';
}
else {
a[i].innerHTML = '<label class="label label-error">Offline</label>';
}
}
DEMO