I have some issues in getting values from datatable that i imported from excel.
i Want to pass the rows that selected (at least can be viewed in alert), here's the case.
the value that i want is like
Name : A. Mused , No HP : 087....
Name : Aida Bugg, No HP : 089....
Name : Allie Grater, No HP : 087...
but the result is just like this screenshot :
result popup alert and data
here's the code :
html
#if (Model != null)
{
<table id="tablePenerima" class="table table-striped table-bordered animate__animated animate__fadeInRight" cellpadding="0" cellspacing="0">
<thead>
<tr>
#foreach (DataColumn col in Model.Tables[0].Columns)
{
<th align="center">#col.ColumnName</th>
}
</tr>
</thead>
<tbody>
#foreach (DataRow row in Model.Tables[0].Rows)
{
<tr >
#foreach (DataColumn col in Model.Tables[0].Columns)
{
<td align="center">#row[col.ColumnName]</td>
}
</tr>
}
</tbody>
</table>
}
and the javascript :
$(document).ready(function () {
var table = $('#tablePenerima').DataTable({
dom: 'Bfrtip',
buttons: [
'selectAll',
'selectNone',
],
select: true
});
$('#tablePenerima tbody').on('click', 'tr', function () {
$(this).toggleClass('selected');
});
$('#btnBlast').click(function () {
var ids = $.map(table.rows('.selected').data(), function (item) {
return item[0]
});
var data = $('#tablePenerima').DataTable().row('.selected').ids();
console.log(ids);
alert("Name:" + ids[0] + "\nNo HP:" + ids[2]);
});
});
I hope all of you can solve my problem because my knowledge in js is still weak. Thanks :)
I have no experience with DataTable package, but i think the problem is your map function. It returns the first row of selected rows.
var ids = $.map(table.rows('.selected').data(), function (item) {
return item[0]
});
Instead of
return item[0]
You should return all selected rows;
return item
In $('#btnBlast').click event
Related
I tried to implement a Dropdown Filter to filter my Datatable like here: Individual column searching (select inputs).
This also works up to the moment when I try to use UIHints to style my output. I think the problem is that my javascript code looks for the old cell content, while the actual cell content has already been changed by my UIHint. What is the best way to make my Drowpdown Filter working anyways?
Thank you in advance!
Here is a part of my code:
Status.cshtml (Display Template for status)
#model short?
#if (Model == 0)
{
<b>Not Set</b>
}
else if (Model == 1)
{
<b>Created</b>
}
else if (Model == 2)
{
<b>Approved</b>
}
else if (Model == 3)
{
<b>Done</b>
}
Index.cshtml (View)
#model IEnumerable<data>
<h2>Data</h2>
<table class="display" id="db_table" style="width:100%">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.month)
</th>
<th>
#Html.DisplayNameFor(model => model.year)
</th>
<th>
#Html.DisplayNameFor(model => model.country)
</th>
<th>
#Html.DisplayNameFor(model => model.status)
</th>
</tr>
</thead>
<tbody>
#for (var i = 1; i < Model.Count(); i++)
{
<tr>
<td>
#Html.DisplayFor(modelItem => Model.ElementAt(i).month)
</td>
<td>
#Html.DisplayFor(modelItem => Model.ElementAt(i).year)
</td>
<td>
#Html.DisplayFor(modelItem => Model.ElementAt(i).country)
</td>
<td>
#Html.DisplayFor(modelItem => Model.ElementAt(i).status)
</td>
</tr>
}
</tbody>
</table>
#section scripts
{
<script src="~/Scripts/Custom/datatable.js"></script>
}
datatable.js
$(document).ready(function () {
$('#db_table').DataTable({
ordering: false,
paging: false,
lengthChange: false,
initComplete: function () {
this.api().columns(3).every(function () {
var column = this;
var select = $('<select><option value=""></option></select>')
.appendTo($(column.header()))
.on('change', function () {
var val = $.fn.dataTable.util.escapeRegex(
$(this).val()
);
column
.search(val ? '^' + val + '$' : '', true, false)
.draw();
});
column.data().unique().sort().each(function (d, j) {
select.append('<option value="' + d + '">' + d + '</option>')
});
});
}
});
});
Okay I found my mistake:
The UIHints edited my cell contents with different styling tags. For example a cell content text was made bold and afterwards looked like <b>text</b>. This means my javascript filtering function was looking for text, when in reality the cells looked like <b>text</b>.
In order to bypass this behavior I created a javascript function, which removes html tags:
function stripString(str) {
return str.replace(/(<([^>]+)>)/gi, "");
}
and used it on the input values:
var val = stripString($.fn.dataTable.util.escapeRegex($(this).val()));
Then it works just fine!
I've been searching on how to achieve this. I got a lot of info from this site, but all couldn't help.
I'm trying to populate a table with the data I got from PHP File Using Ajax
I've been able to get the data, at least into the console. But when i try sending it to the the table, nothing is shown. No errors shown, Just blank.
console.log(newarr)
brings
gives this answer (image)
But when I do this $("#report").html(newarr);, nothing happens.
Here is the code:
ajax
$.post('./process/assetReport.php', data, function(data) {
genData = JSON.parse(data);
var newarr;
for (var key in genData) {
if (data.hasOwnProperty(key)) {
newarr = genData[key];
//console.log(newarr);
$("#report").html(newarr);
}
}
});
php
foreach($all as $item) {
$assetid = $item['assetid'];
$staffid = $item['staffid'];
$row2 = $user->showone('assets', 'assetid', $assetid);
$row3 = $user->showone('staff', 'staffid', $staffid);
$useData[] = array(
'asset' => $row2['name'],
'staff' => $row3['name'],
'cost' => $item['cost']
);
}
echo json_encode($useData);
The table I need to populate
<table class="table" id="reportTable">
<thead>
<tr>
<th>Asset Name</th>
<th>Assigned To</th>
<th>Cost</th>
</tr>
</thead>
<tbody id="report">
</tbody>
<tfoot>
<tr>
<td><button type="button" class="btn btn-success" id="printReport"><i class="glyphicon glyphicon-print"></i> Print</button></td>
</tr>
</tfoot>
</table>
I hope my question is explanatory enough
Thank you
I have created a stub of a JSON array, and shown how to loop through it appending rows to your table as you go. I excluded your key check, as I wasn't sure the relevance. A variation of this code should reside in the callback to your $.post()
data = [{
asset: "steve",
staff: "steve",
cost: '$999,999.99'
}, {
asset: 'bob',
staff:"bob",
cost: '$0.99'
}];
var $row = $("<tr><td></td><td></td><td></td></tr>"); //the row template
var $tr;
$.each(data, function(i, item) {
$tr = $row.clone(); //create a blank row
$tr.find("td:nth-child(1)").text(item.asset); //fill the row
$tr.find("td:nth-child(2)").text(item.staff);
$tr.find("td:nth-child(3)").text(item.cost);
$("#report").append($tr); //append the row
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>Asset Name</th>
<th>Assigned To</th>
<th>Cost</th>
</tr>
</thead>
<tbody id='report'>
<tbody>
</table>
I think you need to user genData[0] instead of genData as your are using $useData[] inside php or user $useData instead of $useData[]
So the code should be look like followings:
$.post( './process/assetReport.php', data, function (data) {
genData = JSON.parse(data);
var newarr;
for(var key in genData[0]) {
if(data.hasOwnProperty(key)){
newarr = genData[key];
//console.log(newarr);
$("#report").html(newarr);
}
}
});
And the php:
foreach ($all as $item) {
$assetid = $item['assetid'];
$staffid = $item['staffid'];
$row2 = $user->showone('assets', 'assetid', $assetid);
$row3 = $user->showone('staff', 'staffid', $staffid);
$useData[] = array(
'asset' => $row2['name'],
'staff' => $row3['name'],
'cost' => $item['cost']
);
}
echo json_encode($useData);
I have a main view that has the following sample table definition.
<table id="myDynamicTable" cellpadding="0" cellspacing="0" width="964px">
<thead>
<tr id="uploadrow_0">
<th" >
Number
</th>
<th">
Remarks
</th>
</tr>
</thead>
<tbody>
#if (Model.myModel.Count > 0)
{
int i = 1;
foreach (var item in Model.myModel)
{
#Html.Partial("myModelPartial", item);
i += 1;
}
}
else
{
#Html.Partial("myModelPartial", viewModel);
}
</tbody>
</table>
I then have a partial view formatted like below
#model myProject.ViewModel.mySampleViewModel
<tr>
#using (Html.BeginCollectionItem("NewRow"))
{
<td class="tdBorder">
#if (Model.Number != 0)
{
#Html.LabelFor(x => Model.Number)
}
else
{
#Html.Label("Number", "0")
}
</td>
<td>
#Html.TextBoxFor(x => Model.Remark, new { id = "Remark"})
</td>
}
</tr>
I'm using this partial view to dynamically add rows to a table in my main view & this part is working fine.
What i'm struggling with is adding the row numbers in the first column of the table i.e (Number column)
Below is how i'm adding the rows to the table in jquery `
$(document).ready(function() {
var tableBody = $('#myDynamicTable tbody');
var url = '#Url.Action("Add", "Report")';
$('#btnAddRow').click(function () {
$.get(url, function (response) {
tableBody.append(response);
//auto number added rows
$('#myDynamicTable tbody tr').each(function (idx) {
$(this).children(":eq(0)").html(idx + 1); //i'm trying to add the row number from here but this isn't working
});
});
});
})`
adding td: got it working.
so this works
//auto number added rows
$('#myDynamicTable tbody tr').each(function (idx) {
$(this).children("td:eq(0)").html(idx + 1);
});
Ref: https://api.jquery.com/eq-selector/
I need to know how can i add a row in this table for each one of the values of the checked checkboxes.
<table class="table table-striped table-hover table-responsive" id="sel_articulos">
<thead>
<tr>
<th>Id</th>
</tr>
</thead>
<tbody></tbody>
</table>
I'm saving a list of checked checkboxes with this code in an array.
$('#modalarticulos').on('hidden.bs.modal', function () {;
var sel_articulos = $("input[name='check_art']:checked").map(function () {
return this.value;
}).get();
console.log(sel_articulos);
showSels();
})
tried with this method but i get all the values from the array in the response
var tbody = $('#sel_articulos tbody');
var props = ["id"];
$.each(sel_articulos, function(i, sel_articulo) {
var tr = $('<tr>');
$.each(props, function(i, prop) {
$('<td>').html(sel_articulos).appendTo(tr);
});
tbody.append(tr);
});
I.E: If i select 5 values i get this on every row of my table.
112113114115117
I am trying to sort a table - so when a user clicks on the table heading, it will sort in ascending/descending order. I've got it to the point where I can sort the table based on the column value. However, I have groupings of table rows (two rows per table body), and I want to sort the columns based on the values in the columns of the first row of each table body, but when it reorders the table, it want it to reorder the table bodies, not the table rows.
<table width="100%" id="my-tasks" class="gen-table">
<thead>
<tr>
<th class="sortable"><p>Name</p></th>
<th class="sortable"><p>Project</p></th>
<th class="sortable"><p>Priority</p></th>
<th class="sortable"><p>%</p></th>
</tr>
</thead>
<tbody>
<tr class="sortable-row" id="44">
<td><p>dfgdf</p></td><td><p>Test</p></td>
<td><p>1</p></td><td><p>0</p></td>
</tr>
<tr>
<td></td>
<td colspan="3"><p>asdfds</p></td>
</tr>
</tbody>
<tbody>
<tr class="sortable-row" id="43">
<td><p>a</p></td>
<td><p>Test</p></td>
<td><p>1</p></td>
<td><p>11</p></td>
</tr>
<tr>
<td></td>
<td colspan="3"><p>asdf</p></td>
</tr>
</tbody>
<tbody>
<tr class="sortable-row" id="40">
<td><p>Filter Tasks</p></td>
<td><p>Propel</p></td>
<td><p>10</p></td>
<td><p>10</p></td>
</tr>
<tr>
<td></td>
<td colspan="3"><p>Add a button to filter tasks.</p></td>
</tr>
</tbody>
</table>
With the following javascript:
jQuery(document).ready(function () {
jQuery('thead th').each(function(column) {
jQuery(this).addClass('sortable').click(function() {
var findSortKey = function($cell) {
return $cell.find('.sort-key').text().toUpperCase() + ' ' + $cell.text().toUpperCase();
};
var sortDirection = jQuery(this).is('.sorted-asc') ? -1 : 1;
var $rows = jQuery(this).parent().parent().parent().find('.sortable-row').get();
jQuery.each($rows, function(index, row) {
row.sortKey = findSortKey(jQuery(row).children('td').eq(column));
});
$rows.sort(function(a, b) {
if (a.sortKey < b.sortKey) return -sortDirection;
if (a.sortKey > b.sortKey) return sortDirection;
return 0;
});
jQuery.each($rows, function(index, row) {
jQuery('#propel-my-tasks').append(row);
row.sortKey = null;
});
jQuery('th').removeClass('sorted-asc sorted-desc');
var $sortHead = jQuery('th').filter(':nth-child(' + (column + 1) + ')');
sortDirection == 1 ? $sortHead.addClass('sorted-asc') : $sortHead.addClass('sorted-desc');
jQuery('td').removeClass('sorted').filter(':nth-child(' + (column + 1) + ')').addClass('sorted');
});
});
});
You need to sort the tbody elements, not the row elements. You said that yourself in your description of the problem, but your code actually sorts rows, not tbodies.
A secondary problem is that your sort treats everything as a string, which breaks when sorting 1-digit numeric strings ("2") against two-digit strings ("10").
To fix, replace this:
var $rows = jQuery(this).parent().parent().parent()
.find('.sortable-row').get();
jQuery.each($rows, function(index, row) {
row.sortKey = findSortKey(jQuery(row).children('td').eq(column));
});
with this:
var $tbodies = jQuery(this).parent().parent().parent()
.find('.sortable-row').parent().get();
jQuery.each($tbodies, function(index, tbody) {
var x = findSortKey(jQuery(tbody).find('tr > td').eq(column));
var z = ~~(x); // if integer, z == x
tbody.sortKey = (z == x) ? z : x;
});
And then replace $rows with $tbodies throughout your script, and row with tbody.
Example:
http://jsbin.com/oxuva5
I highly recommend the jQuery plugin http://tablesorter.com/ instead of rolling your own.
It's fully featured and well supported.