How to print data by current table on page in Laravel 5? - javascript

My problems are:
When I click the print button, it shows the data by text not in table.
I want to print data table depends on the current table show. means
here is on the current page has list of all data and select option.
When I select or filter table it still print all the data. The data
here is collected from database.
After logged in, why does the image for next page not show?
Here is my JavaScript:
<script lang='javascript'>
$(document).ready(function(){
$('#printPage').click(function(){
var data = '<input type="button" value="Print this page" onClick="window.print()">';
data += '<div id="div_print">';
data += $('#report').html();
data += '</div>';
myWindow=window.open('','','width=200,height=100');
myWindow.innerWidth = screen.width;
myWindow.innerHeight = screen.height;
myWindow.screenX = 0;
myWindow.screenY = 0;
myWindow.document.write(data);
myWindow.focus();
});
});
</script>
Blade template:
<tbody id="result">
#foreach($profiles as $profile)
<tr>
<td class="student_id" width="15%">{{$profile->student_id }}</td>
<td class="name" width="30%">{{$profile->student_name }}</td>
<td class="program" width="30%"> {{$profile->program }}</td>
<td class="faculty" width="25%">{{$profile->faculty }} </td>
</tr>
#endforeach
</tbody>
</table>
<p align="center"><button id="printPage">Print</button></p>

Rather than doing the method I suggest that you use a PDF generation plugin such as pdf-laravel.
PDF-LARAVEL :
to output to a file
$router->get('/pdf/output', function() {
$html = view('pdfs.example')->render();
PDF::load($html)
->filename('/tmp/example1.pdf')
->output();
return 'PDF saved';
});
Adding the functionality to your controller
class HomeController extends Controller
{
private $pdf;
public function __construct(Pdf $pdf)
{
$this->pdf = $pdf;
}
public function helloWorld()
{
$html = view('pdfs.example1')->render();
return $this->pdf
->load($html)
->show();
}
If you want to search for other options then go to packagist.org and search for "pdf laravel" and you will find some packages built for Laravel 5 PDF generation.

Answer to the question 2:
I want to print data table depends on the current table show. means
here is on the current page has list of all data and select option.
When I select or filter table it still print all the data. The data
here is collected from database
If you want to filter data and display there, you have two options, either filter data form the controller or you can use jQuery Datatables for that. Link here
All you have to do is:
Add the Js.
https://cdn.datatables.net/1.10.10/css/jquery.dataTables.min.css
Add the css
http://cdn.datatables.net/1.10.10/js/jquery.dataTables.min.js
Call your table.
$(document).ready(function(){
$('#myTable').DataTable();
});

function printData()
{
var print_ = document.getElementById("table_name");
win = window.open("");
win.document.write(print_.outerHTML);
win.print();
win.close();
}
The above function will print the data of a table which are on the current page due to the window.open("") function.

Related

sending html data to view and then sending to controller to update sql database

I have a HTML table where one of the columns value is dynamically added. I have an update button, upon clicking it I want this data to get updated in my sql database. For this, I am planning to first fetch the table data and put into view , then send data to controller and then updating sql.
I am stuck at the first step,
Descibing table below
<thead>
<tr>
<th>ID</th>
<th >Name</th>
<th>Active</th>
<th>Order By</th>
</tr>
</thead>
<tbody>
#if (ViewBag.data != null)
{
foreach (var item in ViewBag.data)
{
<tr>
<td >#item.AutoID</td>
<td #item.Text</td>
<td >#item.Active</td>
<td>#item.OrderBy</td>
</tr>
}
}
</tbody>
</table>
</div>
</div>
<input type="submit" value="Update Preference" class="BtnUpdOrderId" />
</div>
I tried this below js function to fetch the data
$(".BtnUpdOrderId").click(function () {
var tr = $(this).closest('tr');
var id = tr.find('input[name="autoid"]').val();
var text = tr.find('input[name="text"]').val();
var active = tr.find('input[name="active"]').val();
var orderby = tr.find('input[name="orderby"]').val();
alert('type1 : ' + id + ' ' + text + ' ' + active + ' ' + active);
});
but not sure why nothing came in alert
var TableData = new Array();
$('#tblLookup1 tr').each(function (row, tr) {
TableData = TableData + $(tr).find('td:eq(0)').text();
alert(TableData);
});
then tried the above block of code to get data in a variable but still not able to get anything.
Once I get the data I can try sending from view->controller.
So need the following help:
what mistake am I making?
once this is fixed, how to send data to sql? (this is a ado.net based mvc project)
you might want to consider creating a json object:
Creating json object in mvc and returning from controller
then build your table Convert JSON array to an HTML table in jQuery
finally, the update need only post back the json object
https://dontpaniclabs.com/blog/post/2013/02/27/posting-json-data-to-an-mvc-controller-via-ajax/
if you going to use this jason object make sure you use serialization
https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-how-to?pivots=dotnet-6-0
your have to patch these concepts together but there are a lots of tutorials and examples online so it be a good learning experience
I hope this helps
helpful links:
https://www.sqlshack.com/modifying-json-data-using-json_modify-in-sql-server/
Updating a JSON object using Javascript
https://www.geeksforgeeks.org/how-to-convert-json-data-to-a-html-table-using-javascript-jquery/
create json object from html table using selected colums using jquery

How can I bind multi select list items that have been dynamically added using the .net core framework?

I am using .net core 2.2 Razor Pages to build my current project. I want to be able to have 2 multi-select lists in which I pass values from one list to the other and vice versa. I am able to load the left side list with the values required using binding. I also have the buttons to transfer X amount of selected items to the right side list. This is done using jquery. However when I submit my form and get the OnPostAsync The values from the list on the right side are lost and the ones on the left side are as if they where never removed.
I understand that to dynamically add controls that bind to a property you require adding all the necessary attributes. I have compared the generated html from the left list (generated by .net core) to the right side list (generated by me using jquery) and they are identical so I don't see what attributes might be missing...
Below is a sample of the code I am working with.
```html
<table width="100%">
<tr>
<td rowspan="2" class="role-fromto">
<select asp-for="RolesLeft" asp-items="#(new SelectList(Model.RolesLeft, "Id", "Name"))" class="form-control" multiple>
</select>
</td>
<td class="centered">
<a id="role-add" class="button-pointer">>></a>
</td>
<td rowspan="2" class="role-fromto">
<select asp-for="RolesRight" asp-items="#Model.RolesRight" class="form-control" multiple>
</select>
</td>
</tr>
<tr>
<td class="centered">
<a id="role-remove" class="button-pointer"><<</a>
</td>
</tr>
</table>
```
(Please note there is a submit button as well which performs the OnPostAsync)
The properties that are binding are in my C# code. The left side roles are a list of Role objects while on the right side I made a list of SelectListItem which I will later convert in the OnPostAsync method. The left side list is populated in the OnGetAsync method during loading (I am not putting this code here because it works and I want to avoid confusion of bloat code):
```C#
[BindProperty]
public List<Role> RolesLeft { get; set; }
[BindProperty]
public List<SelectListItem> RolesRight { get; set; } = new List<SelectListItem>();
```
Finally the javascript that runs when I select the >> link to move over the selected items to the right side executes the following code:
```JavaScript
$(document).ready(function () {
$("#role-add").on("click", function () {
moveRoles("RolesLeft", "RolesRight");
});
$("#role-remove").on("click", function () {
moveRoles("RolesRight", "RolesLeft");
});
function moveRoles(from, to) {
var items = $("#" + from + " option:selected").map(function () {
return $(this);
}).get();
for (i = 0; i < items.length; i++) {
$("#" + from + " option[value='" + items[i].val() + "']").remove();
$("#" + to).append($('<option />', {
value: items[i].val(),
text: items[i].text()
}));
}
}
});
```
I'm not sure if I missed anything but if so please let me know and I will update the post to provide more information. How can I get this working properly? I have been able to dynamically generate other types of controls and get it to bind but this one I have not had any success.

Tooltip showing hidden values in table format on hover

My site is set up in the following way:
4 user groups. Each user group can see different information. An example would be stock quantity for a store. So the user from London can't see the stock availability for Manchester. This information is taken from the database for EACH item in stock. So if you have a list of 20 items, their individual values will be displayed.
I would like to do the following:
If I, or anyone I give permission to, hovers over the "In Stock" column for their own store, a tooltip table must appear showing the current stock levels for the 3 other stores, for each individual product. So if I hover over item SKU-001, I will only see the stock availability for that item. I had an issue where it was displaying the whole list for each item.
I was thinking of this:
<table>
<tr>
<th>Store1></th>
<th>Store2></th>
<th>Store3></th>
<th>Store4></th>
</tr>
<?php foreach($this->products as $product) { ?>
<tr>
<td id="stock1" title="myFunction">Stock of Item 1st store</td> *If I hover/mouseover here, another table must appear showing only store name and values of "#stock2, #stock3 and #stock4* for the stock item I am hovering on.
<td id="stock2">Stock of Item 2nd store</td>
<td id="stock3">Stock of Item 3rd store</td>
<td id="stock4">Stock of Item 4th store</td>
</tr>
<?php } ?>
</table>
Here is some code I wrote:
function myFunction() {
var x = document.createElement("TABLE");
x.setAttribute("id", "table10");
document.body.appendChild(x);
var y = document.createElement("TR");
y.setAttribute("id", "myTr");
document.getElementById("myTable").appendChild(y);
var z = document.createElement("TD");
var t = document.getElementByID("riyadhbalance").value();
z.appendChild(t);
document.getElementById("myTr").appendChild(z);
However, for some reason this is not working. I have not found a way to include a tooltip. All the stock values are there for each individual item, so I just need to find a way to add the 3 values for the other stores and display them in a table format via a tooltip. That would be ideal.
So basically the tooltip should show the 3 values of the stores which are currently not on display, as the other 3 values are hidden. The user can only see their store's stock levels. But I would like to include this for myself as it would make it easier to view stock levels across the board.
Check this solution with jQuery and Bootstrap Working fiddle
You have four options:
1 - You can dynamically add it to your code on domReady (like the fiddle)
2 - You can directly print the needed html to make the plugin work. Check docs POPOVER or TOOLTIP
<button type="button" class="btn btn-lg btn-danger my_elements" data-toggle="popover" title="Popover title" data-content="And here's some amazing content. It's very engaging. Right?">Click to toggle popover</button>
// and then, just call from javscript
<script>
$('.my_elements').popover(); // or $('.my_elements').tooltip();
</script>
3 - You can create it when you hover any element. Like the following example (this is particulary helpful if you have a lot of elements needing popover/tooltip, which would consume a lot of time and memory to init and handle)
<table>
<thead>
<tr>
<th>SKU</th>
<th>Description></th>
<th>Stock Tooltip</th>
<th>Stock Popover</th>
</tr>
</thead>
<tbody>
<tr><td>SKU-0001</td><td>This is a description for SKU-0001</td><td class="stock_t">5</td><td class="stock_p">5</td></tr>
</tbody>
</table>
<script>
$('.stock_p').on('mouseover', function(){
// get data from AJAX
// create table element
$(this).attr('title', table_element);
$(this).tooltip({
placement: 'top',
trigger: 'hover',
html: true,
container: 'body',
}).tooltip('show');
});
</script>
4 - with AJAX
<?php
// server side PHP
$other_stores_stock = [ "store_1" => 5, "store_2" => 20, "store_3" => 50 ];
header( 'Content-Type: application/json' );
echo json_encode( $other_stores_stock );
?>
//client side JS - like 1st example
<script>
$('.stock_p').on('mouseover', function(){
$.ajax({
url: your_url,
type: 'POST',
data: { your_data: 'get_stock_qty"},
dataType: "json",
async: false,
success: function (res) {
let table_html = '<table><tr><td>'+res['store_1']+'</td><td>'+res['store_2']+'</td><td>'+res['store_3']+'</td></tr></table>';
$(this).attr('title', 'Stock value for other Stores');
$(this).attr('data-placement', 'left');
$(this).attr('data-toggle', 'popover');
$(this).attr('data-trigger', 'hover');
$(this).attr('data-html', true);
$(this).attr('data-content', table_html);
$(this).popover('show');
}
});
});
</script>

Jquery to compare the value of dynamically generated control

Hi I am developing a mvc4 jquery application. I have dynamically generated hidden field and I am binding some value to it as below.
#foreach (var group in Model.detailsbyclientId) {
<tr>
<td> #group.clientName </td>
<td> #group.employeeId </td>
<td> #group.employeeName </td>
<td>#group.Nationality</td>
<td> #group.documentType </td>
<td scope="col">
<input type="button" class="btn btn-primary btn-cons" value="View Document" onclick="showDocumentData('#group.upld_Id');" />
</td>
<td id="Hi">#group.currentStatus</td>
<td><input type="hidden" id="Status" value="#group.currentStatus"/></td>
<td></td>
</tr>
}
In some point of time the value of #group.currentStatus will be NotVerified. For example if I generate 5 rows of data, the value of all 5 rows will be NotVerified. In such a case I want to display some message or else display nothing. So whenever all rows of the data are holding the same value then I want to display a message. This is my jquery function and I have used below logic.
var list = new Array();
$('input[type=hidden]').each(function (i, item) {
list.push($(item).val());
if(list[i]==list[i+1]) {
fun_toastr_notify('success', 'Please verify the document');
} else {
}
});
I am not able to compare each row of data. If all the values are the same then I only want to display my toaster message once. What logic should I use here? Thank you in advance.
I tried as below now.
for(var i=0;i<list.length;i++) {
if(list[i]==list[i+1]) {
fun_toastr_notify('success', 'Please verify the documents');
}
}
Now my problem is that the toaster message will display more than one time. I want to display it only once if all elements are equal.
You may want to consider putting this logic in the code that generates the viewmodel and output a flag to display the message, rather doing it while rendering the view.
This greatly simplifies your logic. An example:
public class YourModel {
public List<ClientDetails> detailsbyclientId {get;set;}
public bool AllClientsUnverified { get { return detailsbyclientId.All(client => client.currentStatus == "Unverified"); } }
}
And then in your view (inside a client <script> block)
if (#Model.AllClientsUnverified) {
fun_toastr_notify('success', 'Please verify the documents');
}

Call controller function from HTML dynamically created

I have a controller which have a function called $scope.removePoster and another one inside the same controller who create a table calling $scope.removePoster like this:
for(var i=0; i < 6 && postersNum >= 0; i++){
...
table += '<td align="center">';
table += '<img width="150" height="175" src="../js/librerias/carousel/images/'+$scope.posters[indexPosters]['image']+'"><br>';
table += '<button type="button" class="btn btn-danger" ng-click="removePoster('+$scope.posters[indexPosters]['id']+')">Delete</button>';
table += '</td>';
...
When I add this table in my HTML the button doesn't call this function.
Sounds like you are using for something like this:
<!-- HTML -->
<table>
<tr ng-repeat="poster in posters | limitTo: 6">
<td align="center">
Poster {{poster.id}}
<img width="15" height="18"
ng-src="../js/librerias/carousel/images/{{poster.image}}" />
<button type="button" class="btn btn-danger"
ng-click="removePoster(poster.id)">
Delete
</button>
</td>
</tr>
</table>
// Controller:
$scope.posters = [];
$scope.getPosters = function (url) {
$http.post(url, {'method' : 1}).success(function (data, status) {
$scope.posters = data;
});
};
$scope.removePoster = function (id) {
$scope.posters.some(function (poster, idx) {
if (poster.id === id) {
$scope.posters.splice(idx, 1);
return true;
}
});
};
See, also, this short demo.
Some highlights:
By using ngRepeat on the <tr> element, we instruct Angular to create as many tr elements as necessary based on the content of posters (subject to the filtering (see below)).
Angular's built-in limitTo filter, filter's the posters array and makes only the first 6 items available to ngRepeat. Conviniently enough, when the content of the posters array changes (e.g. after removing an entry), the whole expression gets re-evaluated creating or removing DOM nodes as necessary.
IMPORTANT
The implementation above is not the proper way to handle things in all aspects. It is the cleanest/easiset way to allow you to wrap your head around Angular's way of building a table dynamically.
Specifically, in a "real-world app", you should have a service bring the data from the server and inject the service into the controller to let it gain access to the data.

Categories

Resources