Export html table with dropdown to Excel OR CSV using javascript - javascript

I have a table that allow user to add more column OR edit existing column. Inside the existing columns there is dropdown list option for editing.
Like Mentioned in the Image:
I want to export this table in csv or in excel with this dropdown validation options. I tried to implement with export2csv() function but its not getting dropdown.
The output of my export2csv() function:
The output I want:
.html Code :
<div class="card-body">
<div class="table-responsive">
<table class="table dataTable" id="fuelData">
<thead>
<tr>
<th>SNO</th>
<th>Month/Year</th>
<th>Fuel Zone</th>
<th>Fuel Price/Litre</th>
<th>Currency</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{% for f in fuelData%}
<tr id="{{f.id}}">
<td>{{ forloop.counter }}</td>
<td>
<span class="editSpan monthyear">{{f.last_modified}}</span>
<input class="form-control editInput monthyear" type="date" name="monthyear" value="{{f.last_modified}}" style="display: none;">
<small class="text-danger" id="err-monthyear"></small>
</td>
<td>
<span class="editSpan fuel_zone">{{f.fuel_zone}}</span>
<input class="form-control editInput fuel_zone" type="text" name="fuel_zone" value="{{f.fuel_zone}}" style="display: none;">
<small class="text-danger" id="err-fuel_zone"></small>
</td>
<td>
<span class="editSpan fuel_price">{{f.fuel_cost}}</span>
<input class="form-control editInput fuel_price" type="number" name="fuel_price" value="{{f.fuel_cost}}" style="display: none;">
<small class="text-danger" id="err-fuel_price"></small>
</td>
<td>
<span class="editSpan fuel_currency">{{f.currency}}</span>
<select class="form-control editInput fuel_currency" name="fuel_currency" style="display: none;">
{% for c in currency %}
<option value="{{c}}">{{c}}</option>
{% endfor %}
</select>
<small class="text-danger" id="err-fuel_currency"></small>
</td>
<td>
<button type="button" class="btn btn-primary editBtn">Edit</button>
<button type="button" class="btn btn-secondary deleteBtn">Delete</button>
<button type="button" class="btn btn-success saveBtn" style="display: none;">Save</button>
<button type="button" class="btn btn-danger confirmBtn" style="display: none;">Confirm</button>
<button type="button" class="btn btn-secondary cancelBtn" style="display: none;">Cancel</button>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
Javascript Code :
<script>
function export2csv(){
let data = "";
const tableData = [];
const rows = document.querySelectorAll("table tr");
for (const row of rows) {
const rowData = [];
for (const [index, column] of row.querySelectorAll("th, td").entries()) {
if ((index + 1) % 3 === 0) {
rowData.push('"' + column.innerText + '"');
} else {
rowData.push(column.innerText);
}
}
tableData.push(rowData.join(","));
}
data += tableData.join("\n");
const a = document.createElement("a");
a.href = URL.createObjectURL(new Blob([data], { type: "text/csv" }));
a.setAttribute("download", "data.csv");
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
</script>
How can I get dropdown option in csv after exporting?
Thanks In advance!!

Related

Laravel, javascript add rows table class select not working

I have this code which works fine. my problem is that when i go to add one or more rows in the table with the button
the select:
<select name = "product_id_product []" id = "product_id_product '. $ request-> count_product.'" class = "form-control js-select2" required>
it is as if it does not take the "js-select2" class
if instead I insert it manually in the index bypassing the whole class it works
I just can't figure out how to do it ..
index.blade:
<div class="card-body" style="text-align: center;">
<button type="button" name="aggiungi_prodotto" id="aggiungi_prodotto" class="btn btn-primary aggiungi_prodotto" style="visibility: visible;"><i class="mdi mdi-playlist-plus"></i>Aggiungi Prodotto</button>
<button type="button" name="aggiungi_accessorio" id="aggiungi_accessorio" class="btn btn-success aggiungi_accessorio" style="visibility: visible;"><i class="mdi mdi-playlist-plus"></i>Aggiungi Accessorio</button>
<button type="button" name="aggiungi_servizio" id="aggiungi_servizio" class="btn btn-warning aggiungi_servizio" style="visibility: visible;"><i class="mdi mdi-playlist-plus"></i>Aggiungi Servizio</button>
<button type="button" name="aggiungi_riga" id="aggiungi_riga" class="btn btn-danger aggiungi_riga" style="visibility: visible;"><i class="mdi mdi-playlist-plus"></i>Aggiungi Riga</button> <br/><br/><br/>
<div class="form-row">
<div class="table-responsive">
<table class="table table-hover ">
<thead>
<tr>
<th width="50%">Prodotto</th>
<th width="10%">Quantità</th>
<th width="10%">Acconto</th>
<th width="10%">Costo</th>
<th width="10%">Sconto TOT</th>
<th width="10%">Azioni</th>
</tr>
</thead>
<tbody id="prodottiRows">
</tbody>
</table>
</div>
</div>
<hr>
</div>
Javascript:
var count_prodotto = 0;
$(document).on('click', '#aggiungi_prodotto', function(){
count_prodotto = count_prodotto + 1;
var categorieID = document.getElementById('categorie_id').value;
var brandID = document.getElementById('brand_id').value;
var modelloID = document.getElementById('modello_id').value;
$.ajax({
type: 'POST',
url: "{{ route('autocomplete.fetch_prodotti') }}",
data: {
'_token': $('input[name=csrf-token]').val(),
'categorie_id':categorieID,
'brand_id':brandID,
'modello_id':modelloID,
'count_prodotto':count_prodotto
},
success:function(data){
$('#prodottiRows').append(data);
}
});
});
Controller:
public function fetch_prodotti(Request $request)
{
$products = Product::with('Multitenantable')
->where("stato_prodotto",'1')
->where("categorie_id",$request->categorie_id)
->where("brand_id",$request->brand_id)
->where("modello_id",$request->modello_id)
->pluck("nome_prodotto","id");
$prodotti = '
<tr id="row_prodotto'.$request->count_prodotto.'">
<td><select name="product_id_prodotto[]" id="product_id_prodotto'.$request->count_prodotto.'" class="form-control js-select2" required>
<option value="">Seleziona Prodotto</option>';
foreach ($products as $key => $product) {
$prodotti .= '<option value="'.$key.'">'.$product.'</option>';
# code...
}
$prodotti .='</select></td>
<td><input type="text" name="quantita_prodotto[]" id="quantita_prodotto'.$request->count_prodotto.'" class="form-control" value="0" required /></td>
<td><input type="text" name="acconto_prodotto[]" id="acconto_prodotto'.$request->count_prodotto.'" class="form-control" value="0" required /></td>
<td><input type="text" name="costo_prodotto[]" id="costo_prodotto'.$request->count_prodotto.'" class="form-control" value="0" required /></td>
<td><input type="text" name="sconto_prodotto[]" id="sconto_prodotto'.$request->count_prodotto.'" class="form-control" value="0" required /></td>
<td data-column="Rimuovi"><button type="button" name="remove_prodotto" id="'.$request->count_prodotto.'" class="btn btn-danger btn-xs remove_prodotto">Rimuovi</button></td>
</tr>';
return response()->json($prodotti);
}

Column cannot be null by using Auth

I'm inserting multiple data into the database. There is an error for my column report_by which is SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'report_by' cannot be null (SQL: insert into 'complaints' ('defect_id', 'image', 'description', 'report_by') values (1, C:\wamp64\tmp\php8E2E.tmp, leak, ?)) Inside column report_by should be the id of the user by using Auth. It's to tell that the complaint made by which users.
users table
id
role
email
typable_id
typable_type
complaints table
id
defect_id
image
description
report_by
ComplaintController.php
<?php
namespace App\Http\Controllers;
use Auth;
use App\Complaint;
use Illuminate\Http\Request;
class ComplaintController extends Controller
{
public function index()
{
return view('buyers.complaint');
}
public function create(Request $request)
{
if (count($request->defect_id) > 0) {
foreach($request->defect_id as $item=>$v) {
$data = array(
'defect_id' => $request->defect_id[$item],
'image' => $request->image[$item],
'description' => $request->description[$item],
'report_by' => $request->user_id,
);
Complaint::insert($data);
}
}
return redirect('/report-form')->with('success','Your report is submitted!');
}
}
complaint.blade.php
<div class="panel-heading">
<h3 class="panel-title"><strong>Make New Report</strong></h3>
</div>
<div class="panel-body">
<div>
<div class="panel">
<table class="table table-bordered">
<thead>
<tr>
<th><center>Type of Defect</center></th>
<th><center>Image</center></th>
<th><center>Description</center></th>
<th><center>Action</center></th>
</tr>
</thead>
<tbody>
<tr>
<td width="20%">
<form action="/report-create" method="post" enctype="multipart/form-data">
{{ csrf_field() }}
<input type="text" class="hidden" id="user_id" value="{{Auth::user()->id}}">
<select class="form-control" name="defect_id[]">
<option value="" selected>Choose Defect</option>
#foreach(App\Defect::all() as $defect)
<option value="{{$defect->id}}">{{$defect->name}}</option>
#endforeach
</form>
</td>
<td width="15%">
<input type="file" class="form-control-file" name="image[]">
</td>
<td width="45%">
<input type="text" class="form-control" name="description[]">
</td>
<td width="10%">
<button type="button" class="btn btn-info btn-sm" id="add-btn"><i class="glyphicon glyphicon-plus"></i></button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<center><button type="submit" class="btn btn-primary">Submit</button></center>
</div>
Here my javascript inside the blade
#section('footer')
<script>
$(document).ready(function () {
$('#add-btn').on('click',function () {
var html = '';
html += '<tr>';
html += ' <td><input type="text" class="hidden" id="user_id" value="{{Auth::user()->id}}"><select class="form-control" name="defect_id[]"><option value="" selected>Choose Defect</option>#foreach(App\Defect::all() as $defect)<option value="{{$defect->id}}">{{$defect->name}}</option>#endforeach</td>';
html += ' <td><input type="file" class="form-control-file" name="image[]"></td>';
html += ' <td><input type="text" class="form-control" name="description[]"></td>';
html += ' <td><button type="button" class="btn btn-danger btn-sm" id="remove-btn"><i class="glyphicon glyphicon-minus"></i></button></td>';
html += '</tr>';
$('tbody').append(html);
})
});
$(document).on('click','#remove-btn',function () {
$(this).closest('tr').remove();
});
</script>
#stop

need to create multiple groups using form in angular6

I need to create multiple groups in the form. when i create a childgroup and enter an input value the same value reflect in another group i known this is due to ngModel but how to overcome this issue. there is another issue i am facing under childGroup there is 2 table when i create another childGroup and add a new table row to that childGroup this will reflect in another childGroup also.
HTML
<fieldset *ngFor="let task of tasks; let a = index">
<legend>childGroup</legend>
<button (click)="deleteRow(a)" class="btn btn-sm btn-circle btn-danger actionMargin rmv-btn">X</button>
<div class="row">
<section class="col col-6">
<label class="label">Name</label>
<label class="input">
<input type="text" class="input-sm" [(ngModel)]="task.Name" name="task[a].Name" required>
</label>
</section>
<section class="col col-6">
<label class="label">Comm</label>
<label class="input">
<input type="text" class="input-sm" [(ngModel)]="task.Config.command" name="task[a].Config.command" required>
</label>
</section>
</div>
<!--Table-->
<section>
<h2>ABC</h2>
<table class="table table-bordered">
<thead>
<tr>
<th class="name">S no.</th>
<th class="name">Label</th>
<th class="name">Value</th>
<th class="name">Dynamic</th>
<th class="name">Action</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let item of task.ports; let i = index">
<td align="center"><label>{{i + 1}}</label></td>
<td><input type="text" [(ngModel)]="item.Label" name="item[i].Label" [ngModelOptions]="{standalone: true}"
class="inputborder" required></td>
<td><input type="number" [disabled]="item[i].boolean" [(ngModel)]="item[i].Value" name="item.Value"
[ngModelOptions]="{standalone: true}" class="inputborder" required></td>
<td><input type="checkbox" [(ngModel)]="item[i].boolean" name="item[i].boolean" class="check"
[ngModelOptions]="{standalone: true}" required><span class="yes">Yes</span></td>
<td align="center"><button (click)="deleteRow(i,'port')" placement="top" tooltip="Remove Port" class="btn btn-sm btn-circle btn-danger actionMargin rmv-btn">X</button></td>
</tr>
</tbody>
</table>
<button type="button" (click)="Addrow('port')" placement="top" tooltip="Add Port" class="btn btn-sm btn-primary posi">Add
abc</button>
</section>
</fieldset>
TS.
tasks= [];
taskObj = { //click on a blue + button i am pushing this object to tasks
Name: "",
Config: {
command: ""
},
artifacts : [],
ports : []
};
// to add a table row
Addrow(i) {
if (i == 'port') {
let num = 0;
this.taskObj.ports.push({
Label: '',
Value: num,
boolean: true
});
} else {
this.taskObj.artifacts.push({
Source: '',
Relative: ''
})
}
console.log(this.tasks);
}
//remove the table row
deleteRow(index, i) {
if (i == "port") {
this.taskObj.ports.splice(index, 1);
} else {
this.taskObj.artifacts.splice(index, 1);
}
}
I the HTML code i have not add 'XYZ' table code because its same as 'ABC' table. how to implement validation to this loop within loop. Please help me with this issue.

Put minimum length in jquery?

I am trying to make an minimum length in my plugin live search in jquery. I am done doing the live search that connected to my table when I searched. But i would like to put some validation through my live search, like the user must input minimum of 3 characters before the search will begin.. I tried to put the minlength through my js but its not working.. Any suggestion why?
View
#extends('layout.default')
#section('content')
<br><br>
<br><br>
<div class="container">
<h4>Live Search using Laravel</h4>
<div class="col-md-6 col-lg-6 pull-right" >
<p class="pull-right">Click on the zip logo to download the file:<p>
<a href="/live_search_laravel.zip" download="live-search(laravel).zip">
<br><br>
<img border="0" src="/images/ziplogo.png" class="pull-right" alt="AngularJS" width="50" height="42">
</a>
</div>
</div>
<br>
<div class="col-md-12 col-sm-6 col-xs-12">
<div class="x_panel">
<div class="x_content">
<table class="search-table table table-hover">
<thead>
<tr>
<th>
Original File Name
</th>
<th>
Change File Name
</th>
<th>
File Extension
</th>
<th>
Image
</th>
<th>
Category
</th>
<th>
Status
</th>
</tr>
</thead>
<tbody>
#foreach($data as $file)
<tr>
<td>{{ $file->original_filename}}</td>
<tD>{{ $file->rs_filename}}</td>
<td>{{ $file->file_extension}}</td>
<td><img src = "files/images/{{ $file->rs_filename}}"></td>
<td>#if($file->category=="1"){{ "Laravel" }}#endif</td>
<td>
#if($file->status=="0")
<form action="/activateImage/{{ $file->id}}" method="post">
<input type="hidden" name="_token" value="{{{ csrf_token() }}}" />
<button type="submit" class="btn btn-primary">Activate</button>
</form>
#else
<form action="{{ url('deactivateImage', ['id' => $file->id]) }}" method="post">
<input type="hidden" name="_token" value="{{{ csrf_token() }}}" />
<button type="submit" class="btn btn-primary">Deactivate</button>
</form>
#endif
</td>
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
</div>
<h4>All Activated Images using Foreach</h4>
#foreach($data as $file)
#if($file->status=="1")
<div class ="row">
<div class ="form-group">
<img src="/files/images/{{ $file->rs_filename }} " width ="50px" height ="50px">
</div>
</div>
#endif
#endforeach
<h4>All Images using the index</h4>
<div class ="row">
<div class ="form-group">
<img src="/files/images/{{ $data[0]['rs_filename']}} " width ="50px" height ="50px">
</div>
</div>
<div class="col-md-6 col-lg-4 pull-right">
<img src="/files/images/{{ $data[1]['rs_filename']}} " width ="50px" height ="50px">
</div>
#stop
#section('select2_js')
<script type="text/javascript" src="/js/live_search_laravel/select2.js"></script>
#stop
The plugin js
/**
**options to have following keys:
**searchText: this should hold the value of search text
**searchPlaceHolder: this should hold the value of search input box placeholder
**/
(function($){
$.fn.tableSearch = function(options){
if(!$(this).is('table')){
return;
}
var tableObj = $(this),
searchText = (options.searchText)?options.searchText:'Search: ',
searchPlaceHolder = (options.searchPlaceHolder)?options.searchPlaceHolder:'',
divObj = $('<div style="font-size:20px;">'+searchText+'</div><br /><br />'),
inputObj = $('<input style="min-width:25%;max-width:50%;margin-left:1%" type="text" placeholder="'+searchPlaceHolder+'" />'),
caseSensitive = (options.caseSensitive===true)?true:false,
searchFieldVal = '',
pattern = '';
inputObj.off('keyup').on('keyup', function(){
searchFieldVal = $(this).val();
if(searchFieldVal.length >= 3)
{
pattern = (caseSensitive)?RegExp(searchFieldVal):RegExp(searchFieldVal, 'i');
tableObj.find('tbody tr').hide().each(function(){
var currentRow = $(this);
currentRow.find('td').each(function(){
if(pattern.test($(this).html())){
currentRow.show();
return false;
}
});
});
}
});
tableObj.before(divObj.append(inputObj));
return tableObj;
}
}(jQuery));
My JS
$(document).ready(function(){
$('table.search-table').tableSearch({
searchText:'Search:'
});
});

How to sum all array values using Angular

I am creating a dynamic form list and in row there is a subtotal value and what I need is to have a grand total. But my problem is I can't sum all the values.
Here's a bit of my code:
//i created a array that will hold all subtotals
$scope.grand_total = [];
//this function is visible in every row
$scope.subTotal = function($index) {
var total = 0;
angular.forEach($scope.quoteHeader.items[$index], function(value){
angular.forEach(value.items, function(v) {
total += v.unit * v.unit_price;
$scope.grand_total.push({
subtotal: total
});
});
});
return total;
}
//this will process the sum but It didn't work
function computeGrandTotal() {
var total = 0;
angular.forEach($scope.grand_total, function(value) {
console.log(value);
});
}
$scope.grandTotal = function() {
var total = 0.00;
computeGrandTotal(); //call the subtotal function
console.log(computeGrandTotal());
return total;
}
Here's the plnkr: http://plnkr.co/edit/Bfd1e5?p=preview
I hope you can help me with this. Thats all thanks :)
You need to store the total at the given index in the sub_total array then
var quotationList = angular.module('quotation_list', []);
quotationList.controller('quoteList', function($scope) {
$scope.quoteHeader = {};
$scope.quoteHeader = {
items: []
}
$scope.json_output = angular.fromJson($scope.quoteHeader); //display json view
$scope.addParticularHeader = function() {
$scope.quoteHeader.items.push({
particular_name: 'SAMPLE PARTICULAR TITLE',
child_label: {
items: []
}
});
}
$scope.removeQuoteHeader = function($index) {
$scope.quoteHeader.items.splice($index, 1);
}
$scope.addParent = function($index) {
//here we will append the new row
//console.log($scope.quoteHeader.items[$index].child_label);
$scope.quoteHeader.items[$index].child_label.items.push({
particular: 'Sample Particular Name',
unit: 1,
unit_label: 'sqm',
unit_price: 0.00,
unit_subtotal: 0.00,
sublevel: {
items: []
}
});
}
$scope.removeParent = function(parent_id, $index) {
$scope.quoteHeader.items[parent_id].child_label.items.splice($index, 1);
}
$scope.addSubLevel = function(parent_id) {
console.log(parent_id);
}
$scope.grand_total = [];
$scope.subTotal = function($index) {
var total = 0;
angular.forEach($scope.quoteHeader.items[$index], function(value) {
angular.forEach(value.items, function(v) {
total += v.unit * v.unit_price;
});
});
$scope.grand_total[$index] = total;
return total;
}
function computeGrandTotal() {
var total = 0;
//console.log($scope.grand_total);
angular.forEach($scope.grand_total, function(value) {
console.log('total', value);
total += value;
});
return total;
}
$scope.grandTotal = function() {
return computeGrandTotal();
}
});
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet" />
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" />
<script src="//code.angularjs.org/1.3.16/angular.js"></script>
<div class="container">
<h1>Quotation List</h1>
<div ng-app="quotation_list" class="row">
<div ng-controller="quoteList">
<div class="row">
<div class="col-md-12 text-right">
<button ng-click="addParticularHeader()" class="btn btn-primary" type="button">
<span class="fa fa-plus"></span>
Add Particular Header</button>
</div>
</div>
<hr />
<div class="row" ng-repeat="item in quoteHeader.items">
<div class="panel panel-default">
<div class="panel-heading">
<h5 contenteditable="" class="panel-title">{{ item.particular_name }} - {{ $index + 1}} <span ng-click="removeQuoteHeader($index)" class="pull-right btn btn-danger">
<span class="fa fa-times"></span>
Remove</span>
</h5>
<div class="clearfix"></div>
</div>
<div class="panel-body">
<div class="table-responsive">
<table class="table table-bordered">
<thead>
<tr>
<td class="text-center">No.</td>
<td class="text-center">Particulars</td>
<td class="text-center">Unit</td>
<td class="text-center">Unit Label</td>
<td class="text-center">Unit(Price)</td>
<td class="text-center">Unit Price(Php)</td>
<td class="text-center"></td>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in quoteHeader.items[$index].child_label.items">
<td class="text-center">{{ $index + 1 }}</td>
<td class="text-center">
<input type="text" ng-model="item.particular" class="form-control" />
</td>
<td class="text-center">
<input type="number" ng-minlength="1" ng-model="item.unit" class="form-control text-center" />
</td>
<td class="text-center">
<select class="form-control">
<option value="sqm">sqm</option>
<option value="lot">lot</option>
<option value="sets">sets</option>
</select>
</td>
<td class="text-center">
<input type="number" ng-model="item.unit_price" class="form-control text-right" />
</td>
<td class="text-center">
<input type="text" readonly="" value="{{ item.unit * item.unit_price | currency: '₱ ' }}" class="form-control text-right" />
</td>
<td class="text-center">
<button ng-click="addSubLevel($parent.$index)" class="btn btn-primary" type="button">
<span class="fa fa-plus"></span>
</button>
<button ng-click="removeParent($parent.$index, $index)" class="btn btn-danger" type="button">
<span class="fa fa-times"></span>
</button>
</td>
</tr>
<tr>
<td ng-show="!quoteHeader.items[$index].child_label.items.length" class="text-center" colspan="7">
<p>No list yet!</p>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td class="text-center" colspan="6">
<button ng-click="addParent($index)" class="btn btn-primary" type="button">
<span class="fa fa-plus"></span>Add Parent</button>
</td>
<td>
<label>Subtotal: <span>{{ subTotal($index) | currency: '₱ ' }}</span>
</label>
</td>
</tr>
</tfoot>
</table>
</div>
</div>
</div>
</div>
<div ng-show="!quoteHeader.items.length" class="row text-center">
<p>No particulars yet!</p>
</div>
<div class="pull-right">
<label>Grand Total:</label>
<p>{{ grandTotal() }}</p>
<!--
<input type="text" class="form-control text-right" value="{{ grandTotal() | currency: '₱ ' }}" readonly />
-->
</div>
<div class="clearfix"></div>
</div>
</div>
</div>

Categories

Resources