How to expand/collapse html table with partial view? - javascript

I am trying to expand/collapse a table row when a button is clicked. For the moment I can only expand the row.
I want to be able to collapse it aswell.
I am using a partial view.
I have tried this: expand/collapse table rows with JQuery but can't get it to work since I am loading data from a sql-database in a foreach loop.
To clarify: This expands the table, but I'm missing the collapse-part of my javascript code. Thanks in advance.
PartialView
<div class="table" id="logtable">
<div class="row">
<div class="cell" id="tableth">
message
</div>
</div>
#foreach (var item in Model.Logs)
{
<div class="row">
<div class="cell" id="tabletd">
<input type="button" name="answer" value="Show Div" onclick="showDiv(#item.id.ToString())" />
#Html.DisplayFor(modelItem => item.message)
</div>
</div>
<div class="row">
<div id="#item.id.ToString()" style="display:none;" class="answer_list">
<strong>Uri:</strong> #item.Uri <br/>
<strong>Method:</strong> #item.Method <br />
<strong>HttpStatus:</strong> #item.HttpStatus <br />
</div>
</div>
Javascript (in my HTML-view)
<script type="text/javascript">
function showDiv(message) {
document.getElementById(message).style.display = "block";
}
</script>

Do you want a toggle function? Check the status of the element and then chose whether to show or hide:
<script type="text/javascript">
function showDiv(message) {
if(document.getElementById(message).style.display == 'block'){
document.getElementById(message).style.display = "none";
}
else{
document.getElementById(message).style.display = "block";
}
}
</script>
Strictly speaking, this is pure javascript and not jQuery. If you really are using jQuery, you can make it even simpler:
function showDiv(message) {
$('#'+message).toggle();
}
You can even even go for a beautiful animation:
function showDiv(message) {
$('#'+message).slideToggle();
}

<style>
#dvExpoByBatchDate .expandExpo {
background-image: url("../Images/Expand.gif");
background-repeat: no-repeat;
background-position: center,center;
}
#dvExpoByBatchDate .expandExpoDisabled {
background-image: url("../Images/ExpandDisabled.gif");
background-repeat: no-repeat;
background-position: center,center;
}
#dvExpoByBatchDate .collapseExpo {
background-image: url("../Images/Collapse.gif");
background-repeat: no-repeat;
background-position: center,center;
}
</style>
//This is WrapperModel which contains all models for different level.
public class WrapperModel
{
public List<Employee> ListEmployee;
public List<Manger> Listmanger;
public List<Programmer> ListProgrammer;
}
#model Model.WrapperModel
<script>
//Default set to collapse Parent Header
$("#dtExposure .relationshipExposure").attr('colspan', 1);
//Hide child columns
$(".subRelationshipExposure").hide();
</script>
<style>
#dtExposure tr th {
cursor: default !important;
}
</style>
<table id="dtExposure" class="dbExposure display">
#if (Model != null)
{
if (Model.ListEmployee!= null) -- Parent Row View
{
#Html.Partial("Exposure/_ParentPartial", Model)
}
if (Model.Listmanger!= null) -- child Row View
{
#Html.Partial("Exposure/_ChildPartial", Model)
}
}
</table>
// Parent Partial View
#model Model.WrapperModel
<thead id="groupHead">
<tr>
<th rowspan="2" style="background-color: #003675"></th>
<th rowspan="2" style="background-color: #003675">ID</th>
<th class="relationshipExposure sorting_disabled" colspan="4" style="background-color: #003675">
FullName <span>&#9658</span>
</tr>
<tr>
#*HiddenSubChildColumn*#
<th style="background-color: #003675">FullName</th>
<th class="subRelationshipExposure" style="background-color: #003675">First Name</th>
<th class="subRelationshipExposure" style="background-color: #003675">Last Name</th>
<th class="subRelationshipExposure" style="background-color: #003675">Phone</th>
</tr>
</thead>
<tbody id="groupBody">
#foreach (var item in Model.ListEmployee)
{
<tr>
<td id="toggleExposureRelationship" class="expandExpo emptyTd" style="background-color:white;border:none"></td>
<td>#item.CDL</td>
<td>
<span id="relationshipExpo" style="color: #0000ff; cursor: pointer">#item.FullName</span>
</td>
<td class="subRelationshipExposure">#item.FirstName</td>
<td class="subRelationshipExposure">#item.LastName</td>
<td class="subRelationshipExposure">#item.Phone</td>
</tr>
}
</tbody>
//Child Partial View
#model Model.WrapperModel
<thead id="customHead">
<tr class="SubExposureCustomer" style="display: none">
<th class="emptyTd"></th>
<th style="background-color: #003675">ID#</th>
<th style="background-color: #003675">Full Name</th>
<th style="background-color: #003675" class="subRelationshipExposure">First Nmae</th>
<th style="background-color: #003675" class="subRelationshipExposure">Last Namen</th>
<th style="background-color: #003675" class="subRelationshipExposure">Phone</th>
</tr>
<tbody id="customBody">
#*Customer Level*#
#foreach (var item in Model.Listmanger)
{
var currCustomerMasterId = item.CUSTOMERMASTERID;
<tr class="SubExposureCustomer" data-currcustomermasterid="#currCustomerMasterId" style="display: none">
<td class="ExpoCustomerIcon expandExpo emptyTd" style="background-color:white;border:none"></td>
<td>#item.ID</td>
<td>#item.FULLNAME</td>
<td class="subRelationshipExposure">#item.FIRSTNAME</td>
<td class="subRelationshipExposure">#item.LASTNAME</td>
<td class="subRelationshipExposure">#item.PHONE</td>
</tr>
//For Pure MVC Grid Collapse
function ToggleExposure(“relationshipExposure”, “subRelationshipExposure”, 4) {
$(document).on("click", "." + className, function (e) {
var selfExposre = $("." + className);
var subSelfExposre = $("." + subclassName);
if (selfExposre.attr('colspan') == colspan) {
subSelfExposre.toggle();
selfExposre.attr('colspan', 1);
isCollpase = false;
}
else {
subSelfExposre.toggle();
selfExposre.attr('colspan', colspan);
isCollpase = true;
}
var varId = selfExposre.find("span");
varId.empty();
isCollpase ? varId.html("&#9668") : varId.html("&#9658");
});
}

Related

How do i get the dynamic table displayed as a popup?

I have this piece of code which computes the difference between the rows of two selected tables and display the result on click of button. How can I display the result in a pop up? Basically I want the resultant table to come as popup, so that when we close the popup the tables checkbox are again reset.
Edit: I tried using modals but it seems to be not working. Can anyone please help where I am going wrong
var selectedRows = document.getElementsByClassName('selected');
limit = 0; //set limit
checkboxes = document.querySelectorAll('.checkboxdiv input[type="checkbox"]');
function checker(elem) {
if (elem.checked) {
limit++;
} else {
limit--;
}
for (i = 0; i < checkboxes.length; i++) {
if (limit == 2) {
if (!checkboxes[i].checked) {
checkboxes[i].disabled = true;
}
} else {
if (!checkboxes[i].checked) {
checkboxes[i].disabled = false;
}
}
}
}
for (i = 0; i < checkboxes.length; i++) {
checkboxes[i].onclick = function () {
checker(this);
}
}
var checkedArray;
function myFunction(event) {
event.target.parentElement.parentElement.className =
event.target.checked ? 'selected' : '';
var elements = document.getElementsByTagName("INPUT");
checkedArray = new Array();
for (var i = 0; i < elements.length; i++) {
if (elements[i].type === 'checkbox' && elements[i].checked) {
checkedArray.push(elements[i].id);
}
}
console.log(checkedArray);
}
$(".btn[data-target='#myModal']").click(function() {
var modalBody = $('<div id="modalContent"></div>');
var table;
const buildTable = (arr) => {
table = document.querySelector("#diff-table");
if (table) table.remove();
table = document.createElement("table");
table.id = "diff-table";
const thead = document.createElement("thead"),
thA = document.createElement("th"),
thB = document.createElement("th"),
thDiff = document.createElement("th");
thA.innerText = "Plan A";
thB.innerText = "Plan B";
thDiff.innerText = "Difference";
thead.append(thA, thB, thDiff);
table.append(thead);
arr.forEach((i) => {
const tr = document.createElement("tr"),
tdA = document.createElement("td"),
tdB = document.createElement("td"),
tdDiff = document.createElement("td");
tdA.innerText = "$" + i["planA"];
tdB.innerText = "$" + i["planB"];
tdDiff.innerText = "$" + i["diff"];
tr.append(tdA, tdB, tdDiff);
table.append(tr);
});
document.body.append(table);
};
const checked = document.querySelectorAll(":checked"),
arr = [];
if (checked.length !== 2) return;
const plans = document.querySelectorAll(":checked"),
planA = plans[0].closest("table").querySelectorAll("td"),
planB = plans[1].closest("table").querySelectorAll("td");
planA.forEach((cell, i) => {
const valA = +cell.innerText.replace(/[^\d.-]/g, '');
const valB = +planB[i].innerText.replace(/[^\d.-]/g, '');
arr.push({ planA: valA, planB: valB, diff: valA - valB });
});
buildTable(arr);
modalBody.append(table);
$('.modal-body').html(modalBody);
})
.table_container {
float: left;
width: 25%;
}
.container::after {
content: "";
clear: both;
display: table;
}
table {
margin: 0 auto;
border-radius: 10px;
}
tr {
padding: 15px;
text-align: center;
}
td {
color: black;
text-align: center;
vertical-align: middle;
border: 1px double white;
height: 50px;
background-color: light-grey;
width: 272px;
}
.sub_text {
font-size: 12px;
font-style: italic;
color: #0071ce;
font-weight: 100;
}
th {
background-color: #0071ce;
text-align: center;
padding: 10px;
border-top-left-radius: 10px;
border-top-right-radius: 10px;
color: white;
font-weight: bold;
}
.header {
color: #0071ce;
font-weight: bold;
padding: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<div class="container">
<div class="table_container">
</div>
<div class="table_container">
<table id="table1" class="checkboxdiv">
<tr>
<th>Tab A<input type="checkbox" id=" 1" name="table1" value="table1"
onchange="myFunction(event)"> </th>
</tr>
<tr>
<td>$133.90</td>
</tr>
<tr>
<td>$161.30</td>
</tr>
<tr>
<td>$53.30</td>
</tr>
<tr>
<td>$186.20</td>
</tr>
<tr>
<td>HSA match:up to $350</td>
</tr>
<tr>
<td>HSA match:up to $700</td>
</tr>
<tr>
<td>$3000</td>
</tr>
</table>
</div>
<div class="table_container">
<table id="table2" class="checkboxdiv">
<tr>
<th>Tab B <input type="checkbox" id="2" name="table2" value="table2"
onchange="myFunction(event)"></th>
</tr>
<tr>
<td>$33.90</td>
</tr>
<tr>
<td>$161.30</td>
</tr>
<tr>
<td>$53.30</td>
</tr>
<tr>
<td>$186.20</td>
</tr>
<tr>
<td>HSA match:up to $350</td>
</tr>
<tr>
<td>HSA match:up to $700</td>
</tr>
<tr>
<td>$3000</td>
</tr>
</table>
</div>
<div class="table_container">
<table id="table3" class="checkboxdiv">
<tr>
<th>Tab C<input type="checkbox" id="3" name="table3" value="table3"
onchange="myFunction(event)"> </th>
</tr>
<tr>
<td>$33.90</td>
</tr>
<tr>
<td>$161.30</td>
</tr>
<tr>
<td>$53.30</td>
</tr>
<tr>
<td>$186.20</td>
</tr>
<tr>
<td>HSA match:up to $350</td>
</tr>
<tr>
<td>HSA match:up to $700</td>
</tr>
</table>
</div>
</div>
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal">
Launch demo modal
</button>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content"></div>
</div>
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body"></div>
</div>
</div>
</div>
You can use modals to display your differences between your tables as a popup when they selected. Assign modals' close button as a reset button as well via JS.
modals: https://getbootstrap.com/docs/4.0/components/modal/
Edit:
I couldn't find the line for calling your js file in your code. Can you add this line to the end of your html-body section?
You can add a console.log() line to your js file, so you can see if your js and html files are connected or not on the browser. (via insperctor-console)
Also, I couldn't find the line that you're activating your modal. You should change its class list. fade means it will not display on the browser. You should remove it and add show instead.
Edit-2:
I am not familiar with $ so I am adding the JS which is working. Please try the below things and if there will be a problem, edit your code below and leave me a comment.
in your js file, follow the steps I wrote. You should see an alarm when you click your modal button. You need to fill it up:
document.getElementById('modalButton').addEventListener('click', function() {
alert('hi');
// step - 1: clean the inner of previous modal, if it has
// step - 2: add the result of comparing two table elements
// step - 3: remove 'fade' from modal's class and add 'show'
})
in your html (add an id to your modal button, it will be easier to select):
<button type="button" id="modalButton" class="btn btn-primary" data-toggle="modal" data-target="#myModal">Launch demo modal</button>

How to check if the table has a class or not using hasClass function of jQuery?

I have a problem on the onclick function of table b the function does not determine if table A has a class of selected_upsize or not
Scenario:
Table B has a list of item and also in table A.
now when I click one of the items in Table B, the on click function will do the condition if table A has a class of selected_upsize or not, To make the scenario short.
if the table A has a class of (selected_upsize) then it will alert something, else the item of that I clicked in table B will append on table A.
I have here my output
I have here my function to my Onclick function
$(".customer_edit_table_chaining_condiments").on('click',function(e){
//this is the item of table B that will append if the table A has no class
var customer_edit_condimentsScreenNameClicked = $(this).closest('tr').find('.customer_edit_condimentsScreenNameClicked').text();
var customer_edit_condimentsScreenPriced = $(this).closest('tr').find('.customer_edit_condimentsScreenPriced').text();
$(".customer_edit_table_chaining_condiments").on('click',function(e){
//this is the item of table B that will append if the table A has no class
var customer_edit_condimentsScreenNameClicked = $(this).closest('tr').find('.customer_edit_condimentsScreenNameClicked').text();
var customer_edit_condimentsScreenPriced = $(this).closest('tr').find('.customer_edit_condimentsScreenPriced').text();
if($('#noun_chaining_order').find('tr.selected_upsize').length){
alert('You can"t upsize the item');
}else{
$('table#noun_chaining_order').append('<tr class="" id="append_imaginary_upsize_condiments"><td contenteditable="true">-</td><td>'+customer_edit_condimentsScreenNameClicked+'</td><td>'+customer_edit_condimentsScreenPriced+'</td></tr>');
$('tr#append_imaginary_upsize_condiments').addClass('selected_upsize');
}
})
My Html Table A
<table class="table table-hover upsize_check" id="noun_chaining_order" style="border:none;">
<thead>
<tr style="font-size: 15px; color:white;">
<th scope="col">Qty</th>
<th scope="col">Condiments</th>
<th scope="col">Price</th>
</tr>
</thead>
<tbody style="font-size:14px; color:white;" class="tbody_noun_chaining_order">
</tbody>
Table B
<table class="table table-striped table-bordered " id="customer_table_update_chain_order" style="width:100%">
<div class="content-noun" style="text-align: center;">
<thead>
<tr style="background: linear-gradient(-20deg, #00e4d0, #5983e8); color:white;" >
<th>Condiment Screen Name</th>
<th>Condiment Price</th>
<th>Condiment Image</th>
</tr>
</thead>
</div>
<tbody>
</tbody>
$(".customer_edit_table_chaining_condiments").on('click',function(e){
//this is the item of table B that will append if the table A has no class
var customer_edit_condimentsScreenNameClicked = $(this).closest('tr').find('.customer_edit_condimentsScreenNameClicked').text();
var customer_edit_condimentsScreenPriced = $(this).closest('tr').find('.customer_edit_condimentsScreenPriced').text();
//here will check if table A has selected upsize or not
//THE BELOw LINE WILL RETURN ALL THE ELEMENTS WITH SELECTED_UPSIZE CLASS IF WE HAVE .SELECTED_UPSIZE IN THE FIND METHOD, THUS THE BELOW LINE WILL ALWAYS BE TRUE
$('table#noun_chaining_order').find('.upsize_check').each(function(){
//INSTEAD IF YOU SEARCH FOR THE ELEMENTS WITH A DIFFERENT CLASS as in the above line of code, THAT MIGHT OR MIGHT NOT HAVE THE SELECTED_UPSIZE CLASS WITH IT, THEREFORE MAKING THE BELOW STATEMENTS LEGAL
if ($(this).hasClass('selected_upsize')) {
alert('You can"t upsize the item');
}
else
{
$('table#noun_chaining_order').append('<tr class="" id="append_imaginary_upsize_condiments"><td contenteditable="true">-</td><td>'+customer_edit_condimentsScreenNameClicked+'</td><td>'+customer_edit_condimentsScreenPriced+'</td></tr>');
$('tr#append_imaginary_upsize_condiments').addClass('selected_upsize');
}
});
});
ADDING THE SOLUTION BELOW....
HTML
<table class="table table-hover" id="noun_chaining_order" style="border:none;">
<thead>
<tr style="font-size: 15px; color:white;">
<th scope="col">Qty</th>
<th scope="col">Condiments</th>
<th scope="col">Price</th>
</tr>
</thead>
<tbody style="font-size:14px; color:white;" class="tbody_noun_chaining_order">
</tbody>
<table class="table table-striped table-bordered " id="customer_table_update_chain_order" style="width:100%">
<div class="content-noun" style="text-align: center;">
<thead>
<tr style="background: linear-gradient(-20deg, #00e4d0, #5983e8); color:white;" >
<th>Condiment Screen Name</th>
<th>Condiment Price</th>
<th>Condiment Image</th>
</tr>
</thead>
</div>
<tbody>
</tbody>
JAVASCRIPT
$("#customer_table_update_chain_order tbody tr").on('click',function(e){
//this is the item of table B that will append if the table A has no class
var customer_edit_condimentsScreenNameClicked = $(this).find('.customer_edit_condimentsScreenNameClicked').text();
var customer_edit_condimentsScreenPriced = $(this).find('.customer_edit_condimentsScreenPriced').text();
//here will check if table A has selected upsize or not
$('table#noun_chaining_order tbody tr').each(function(){
if ($(this).hasClass('selected_upsize')) {
sameRow = true;
}
else
{
sameRow =false;
$('table#noun_chaining_order').append('<tr class="" id="append_imaginary_upsize_condiments"><td contenteditable="true">-</td><td>'+customer_edit_condimentsScreenNameClicked+'</td><td>'+customer_edit_condimentsScreenPriced+'</td></tr>');
$('tr#append_imaginary_upsize_condiments').addClass('selected_upsize');
}
});
if(sameRow){
alert('You can"t upsize the item');
}
});
Please try this.
If my understanding is correct this should work.
$(".customer_edit_table_chaining_condiments").on('click',function(e){
//this is the item of table B that will append if the table A has no class
var customer_edit_condimentsScreenNameClicked = $(this).closest('tr').find('.customer_edit_condimentsScreenNameClicked').text();
var customer_edit_condimentsScreenPriced = $(this).closest('tr').find('.customer_edit_condimentsScreenPriced').text();
if($('#noun_chaining_order').find('tr.selected_upsize').length){
alert('You can"t upsize the item');
}else{
$('table#noun_chaining_order').append('<tr class="" id="append_imaginary_upsize_condiments"><td contenteditable="true">-</td><td>'+customer_edit_condimentsScreenNameClicked+'</td><td>'+customer_edit_condimentsScreenPriced+'</td></tr>');
$('tr#append_imaginary_upsize_condiments').addClass('selected_upsize');
}
})

docent display pop up with table id

When I click on my button "Select" it should show me the HTML popup, and for some reason is not happening.
Could it be some id problem or hard code?
The main idea is to click and bring some kind of list reading from a random array list.
Below: my .js with the call back id and display.
Any ideas?
<!-- This hosts all HTML templates that will be used inside the JavaScript code -->
<table class ="cls-{id} active-{active}" style="display: none;" width="100%" id="rowTemplate">
<tr class ="bb cls-{id} active-{active}">
<td class="active-{active}" id="{id}-question" width="70%">{question}</td>
<td class="cls-{id} active-{active}" width="30%">
<button class="buttons" step="0.01" data-clear-btn="false" style="background: #006b54; color:white !important ;" id="{id}-inspectionResult"></button>
</td>
</tr>
</table>
<div id="projectPopUp" class="popup-window" style="display:none">
<div class="popuptitle" id="details-name"></div>
<table width="100%" id="detailsgrid">
<tr>
<td style="text-align:left">Start Time</td>
<td> <select id="details-startTime" data-role="none"></select></td>
</tr>
<tr>
<td style="text-align:left">End Time</td>
<td> <select id="details-endTime" data-role="none"></select></td>
</tr>
</table>
<div>
<button class="smallButton" onClick="closeProjectPopup()">Cancel</button>
<button class="smallButton" onClick="submitProjectPopup()">Submit</button>
</div>
</div>
<table style="display: none;" id="sectionRowTemplate">
<tr width="100%" class="bb cls-{id}-row2 sectionheader">
<td class="cls-{id}" colspan="3">{question}</td>
</tr>
</table>
Javascript code:
var buildQuestionnaire = function(){
parseInitialDataHolder();
for (var i = 0; i < ARRAY_OF_QUESTIONS.length; i++){
var id = i;
var data = {
id: id,
question: ARRAY_OF_QUESTIONS[i].question,
inspectionResult: '',
active: true
};
var initialdata = initialdataholder[id];
if(initialdata) {
data = initialdata;
}
dataholder.push(data);
if (typeof ARRAY_OF_QUESTIONS[i].header == 'undefined') {
$('#questionsTable tbody').append(Utils.processTemplate("#rowTemplate tbody", data));
$("#" + id + "-inspectionResult").text(data.inspectionResult || 'Select');
$("#" + id + "-inspectionResult").click(resultHandler.bind(data));
updateActiveStatus(data);
commentvisibilitymanager(data);
}
else {
$('#questionsTable tbody').append(Utils.processTemplate("#sectionRowTemplate tbody", data));
}
}
}
//to show the popup
$('#projectPopUp').show();
//to close the popup
$('#projectPopUp').hide();
$(document).ready(function() {
buildQuestionnaire();
});

how do i make table data occupy entire table row with javascript?

When the button is clicked, the table contents change their layout. i'd like to retain the table layout to be like it was before JavaScript function was executed. i am new to Javascript
function toggle(button)
{
if(document.getElementById("1").value=="Show upcoming"){
document.getElementById("1").value="Show previous";
//hide previous
document.getElementById("before").style.display="none";
//show upcoming
document.getElementById("forward").style.display="block";
//attempt at filling whole row
document.getElementById("forward").style.width="100%";
}
else if(document.getElementById("1").value=="Show previous"){
document.getElementById("1").value="Show upcoming";
//show previous
document.getElementById("before").style.display="block";
//attempt at filling whole row
document.getElementById("before").style.width="100%";
//hide upcoming
document.getElementById("forward").style.display="none";
}
}
.table1, .table2{
width:100%;
}
.table2{
display:none;
}
<input type="button" id="1" value="Show previous" onclick="toggle(this);"/>
<table class="table1" cellpadding="10" cellspacing="1" border="1" id="forward" width="100%">
<tr>
<td class="date">
<div class="datee" align="center">Tommorrow</div>
</td>
</tr>
</table>
<table class="table2" cellpadding="10" cellspacing="1" border="1" id="before" width="100%">
<tr>
<td class="duvha" >
<div class="datee" align="center">yesterday</div>
</td>
</tr>
</table>
Use display:table instead of display:block.
function toggle(button) {
if (document.getElementById("1").value == "Show upcoming") {
document.getElementById("1").value = "Show previous";
//hide previous
document.getElementById("before").style.display = "none";
//show upcoming
document.getElementById("forward").style.display = "table";
} else if (document.getElementById("1").value == "Show previous") {
document.getElementById("1").value = "Show upcoming";
//show previous
document.getElementById("before").style.display = "table";
//hide upcoming
document.getElementById("forward").style.display = "none";
}
}
.table1, .table2 {
width: 100 % ;
}
.table2 {
display: none;
}
<input type="button" id="1" value="Show previous" onclick="toggle(this);" />
<table class="table1" cellpadding="10" cellspacing="1" border="1" id="forward" width="100%">
<tr>
<td class="date">
<div class="datee" align="center">Tommorrow</div>
</td>
</tr>
</table>
<table class="table2" cellpadding="10" cellspacing="1" border="1" id="before" width="100%">
<tr>
<td class="duvha">
<div class="datee" align="center">yesterday</div>
</td>
</tr>
</table>
Change your javascript to below code.
Table are always display:table;
function toggle(button)
{
if(document.getElementById("1").value=="Show upcoming"){
document.getElementById("1").value="Show previous";
//hide previous
document.getElementById("before").style.display="none";
//show upcoming
document.getElementById("forward").style.display="block";
//attempt at filling whole row
document.getElementById("forward").style.width="100%";
}
else if(document.getElementById("1").value=="Show previous"){
document.getElementById("1").value="Show upcoming";
//show previous
document.getElementById("before").style.display="block";
//attempt at filling whole row
document.getElementById("before").style.width="100%";
//hide upcoming
document.getElementById("forward").style.display="none";
}
}

I want to convert my view as it is in the picture to a downloadable pdf file in mvc, c#, or JS

[This] 1 is my view. After the button click, I want to embed this view as a picture or by HTML with CSS to a pdf file. This pdf file gets downloaded on button click.I tried lots of methods like itextsharp, jsPDF, phantomJS but I still have no clue how to achieve it. Can anyone help?
function start() {
var table = tableToJson($('#StudentInfoListTable').get(0))
var doc = new jsPDF('p', 'pt', 'a1', true);
doc.cellInitialize();
$.each(table, function (i, row) {
$.each(row, function (j, cell) {
doc.cell(10, 50, 120, 50, cell, i); // 2nd parameter=top margin,1st=left margin 3rd=row cell width 4th=Row height
})
})
doc.save('sample-file.pdf');
}
function tableToJson(table) {
var data = [];
// first row needs to be headers
var headers = [];
for (var i = 0; i < table.rows[0].cells.length; i++) {
headers[i] = table.rows[0].cells[i].innerHTML.toLowerCase().replace('/ /gi', '');
}
// go through cells
for (var i = 0; i < table.rows.length; i++) {
var tableRow = table.rows[i];
var rowData = {};
for (var j = 0; j < tableRow.cells.length; j++) {
rowData[headers[j]] = tableRow.cells[j].innerHTML;
}
data.push(rowData);
}
return data;
}
body{
background: url("");
background-attachment: fixed;
background-repeat: no-repeat;
}
.content {
width: 100%;
min-height: 400px;
}
.box-header {
background-color: #838060;
height: 50px;
border-top-left-radius: 10px;
border-top-right-radius: 10px;
color: white;
}
.box-header h4 {
position: relative;
top: 10px;
}
.box {
background-color: whitesmoke;
position: relative;
width: 100%;
font-size:28px;
}
.middle{
width:200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.2/jspdf.min.js"></script>
<div class="card">
<div class="card-body">
<table cellpadding="30" class="table table-striped" id="StudentInfoListTable">
<tr>
<td><img src="#Model.img" alt="" height="200" width="200" /></td>
<td class="middle"></td>
<td>LICENSE ID - #Html.DisplayFor(m => m.LicenseID)</td>
</tr>
<tr>
<td>NAME: </td>
<td class="middle"></td>
<td>#Html.DisplayFor(m => m.Name)</td>
</tr>
<tr>
<td>#Html.DisplayFor(m => m.Relo) </td>
<td class="middle"></td>
<td>#Html.DisplayFor(m => m.careOf)</td>
</tr>
<tr>
<td>GENDER: </td>
<td class="middle"></td>
<td>#Html.DisplayFor(m => m.gender)</td>
</tr>
<tr>
<td>BLOOD GROUP: </td>
<td class="middle"></td>
<td>#Html.DisplayFor(m => m.blood)</td>
</tr>
<tr>
<td>DATE OF BIRTH: </td>
<td class="middle"></td>
<td>#Html.DisplayFor(m => m.date)</td>
</tr>
<tr>
<td>CONTACT NO: </td>
<td class="middle"></td>
<td>#Html.DisplayFor(m => m.Mobile)</td>
</tr>
<tr>
<td>ADDRESS: </td>
<td class="middle"></td>
<td>#Html.DisplayFor(m => m.Address)</td>
</tr>
<tr>
<td>Signature </td>
<td class="middle"></td>
<td><img src="#Model.sign" alt="" style="background-color:white;"/></td>
</tr>
</table>
<br/><br/>
<button onclick="start()" class="btn btn-block btn-primary">download</button>
</div>
</div>
Tried this way but doesn't render the CSS, instead it generates this see here.
You can Post the HTML string to server and convert it to PDF.
Here is the demo :
HTML : (Obviously you can use your existing HTML)
<div id="dvTable">
<table cellspacing="0" rules="all" border="1">
<tr>
<th scope="col" style="width: 120px;background-color:#D20B0C">
Customer Id
</th>
<th scope="col" style="width: 150px;background-color:#D20B0C">
Name
</th>
<th scope="col" style="width: 100px;background-color:#D20B0C">
Country
</th>
</tr>
<tr>
<td>
ALFKI
</td>
<td>
Maria Anders
</td>
<td>
Germany
</td>
</tr>
<tr>
<td>
ANATR
</td>
<td>
Ana Trujillo
</td>
<td>
Mexico
</td>
</tr>
</table>
</div>
<input type="hidden" id="hfTableHTML" name="Table_HTML" />
<hr />
<asp:Button Text="Export" runat="server" OnClick="Export" OnClientClick="SetHTML()" />
<script type="text/javascript">
function SetHTML() {
document.getElementById("hfTableHTML").value = document.getElementById("dvTable").innerHTML;
}
</script>
Namespaces:
using System.IO;
using System.Text;
using System.Data;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html.simpleparser;
C# function:
protected void Export(object sender, EventArgs e)
{
//Export HTML String as PDF.
string html = Request.Form["Table_HTML"];
StringReader sr = new StringReader(html);
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
PdfWriter writer = PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
htmlparser.Parse(sr);
pdfDoc.Close();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=Table.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Write(pdfDoc);
Response.End();
}
OR For MVC/C# you can use : Rotativa http://nuget.org/packages/Rotativa. It's based on wkhtmltopdf.
install it from nuget : Install-Package Rotativa -Version 1.7.3 and usage is simple :
public ActionResult PrintIndex()
{
return new ActionAsPdf("Index", new { name = "Giorgio" }) { FileName = "Test.pdf" };
}
You can define an action that returns an ActionResult of the type ActionAsPdf (RouteAsPdf is also available). where name = "Giorgio" is a route parameter.

Categories

Resources