Saving contenteditable Content Changes - asp.net-mvc-5

Good Day! I am a newbie in asp.net MVC 5 and is working on a form where one cell is editable then it will be saved in the database, along with the values of the other cells. I've managed to make the cell editable using contenteditable="true" . This is my View:
<div class="container">
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<div class="col-lg-12">
<div class="col-lg-6"></div>
<div class="col-lg-6">
<div class="form-horizontal">
<div class="form-group">
#Html.LabelFor(m => m.CUSTOMER_ID, "Customer Name", new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("CUSTOMER_ID", ViewBag.CustomerName as IEnumerable<SelectListItem>, "--Select Customer--", new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ORDER_DUE_DATE, "Due Date", htmlAttributes: new { #class = "col-lg-5" })
<div class="col-lg-7">
#Html.TextBoxFor(model => model.ORDER_DUE_DATE, "{0:yyyy-MM-dd}", new { #class = "form-control", #type = "date" })
#Html.ValidationMessageFor(model => model.ORDER_DUE_DATE, "", new { #class = "text-danger" })
</div>
</div>
</div><!--form-horizontal-->
</div>
</div><!--col lg 12-->
<table id="tbl_orderItems" class="table table-striped table-bordered table-hover dt-responsive nowrap" cellspacing="0">
<thead>
<tr>
<th>Item Code</th>
<th>Quantity</th>
<th>Unit</th>
<th>Item Description</th>
<th>Status</th>
<th>Action</th>
</tr>
</thead>
#if (TempData["listOrder"] != null)
{
foreach (var items in TempData["listOrder"] as List<ebms.ViewModels.OrderItems>)
{ #Html.HiddenFor(modelItem => items.Id)
<tr>
<td>#items.PRODUCT_CODE</td>
<td contenteditable="true">#items.iQuantity</td>
<td>#items.MEASUREMENT_NAME</td>
<td>#items.ITEM_DESCRIPTION</td>
<td>#items.tmpStatus</td>
<td>
#Html.ActionLink("Remove", "Remove", new { id = items.Id },
new { onclick = "return confirm('Are sure want to remove?');" })
</td>
</tr>
}
}
</table>
<div id="menu1">
<ul>
<li>
<center><a>Select an Item</a></center>
<ul>
<li><a href='#Url.Action("Products", "Sales")'>Products </a></li>
</ul>
</li>
</ul>
</div>
<div class="form-group">
<div class="col-lg-3 pull-right">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</div>
}
</div>
I've put the contenteditable="true" in the quantity because it is the cell that should be editable. Most of the other values in there are from this form:
It will then be passed on to this form and the quantity should be editable.
Then the Customer will be chosen and the Order Due Date will be put in there as well. My problem is, the value that is typed to the editable cell is not saved in to the database. Can someone help me on how to use contenteditable="true" properly and then save it to the database? Thank you in advanced!

Related

Template not rendering Django (NoReverseMatch)

I am not exactly sure what the issue is but I have this code in my project that once I select a date it will bring up a table with the name of students in my classroom but Django keeps telling me that there isnt NoReverseMatch. i have double check and everything is fine but not sure why it not working.
ERROR SHOWN
Reverse for 'attendance-page' with arguments '('',)' not found. 1 pattern(s) tried: ['attendance/(?P[0-9]+)\Z']
urls.py
path('attendance_class', views.attendance_class, name='attendance-class'),
path('attendance/<int:classPK>', views.attendance, name='attendance-page'),
path(r'attendance/<int:classPK>/<str:date>',views.attendance, name='attendance-page-date'),
path('save_attendance', views.save_attendance, name='save-attendance'),
views.py
#login_required
def attendance_class(request):
classes = Room.objects.all()
context = {}
context['classes'] = classes
return render(request, 'school/attendance_page.html', context)
#login_required
def attendance(request, classPK=None, date=None):
_class = Room.objects.get(id=classPK)
students = Student.objects.filter(id__in=ClassStudent.objects.filter(classIns=_class).values_list('student')).all()
context = {}
context['class'] = _class
context['date'] = date
att_data = {}
for student in students:
att_data[student.id] = {}
att_data[student.id]['data'] = student
if not date is None:
date = datetime.strptime(date, '%Y-%m-%d')
year = date.strftime('%Y')
month = date.strftime('%m')
day = date.strftime('%d')
attendance = Attendance.objects.filter(
attendance_date__year=year, attendance_date__month=month, attendance_date__day=day, classIns=_class).all()
for att in attendance:
att_data[att.student.pk]['type'] = att.type
print(list(att_data.values()))
context['att_data'] = list(att_data.values())
context['students'] = students
return render(request, 'school/attendance_control.html')
def save_attendance(request):
resp = {'status': 'failed', 'msg': ''}
if request.method == 'POST':
post = request.POST
date = datetime.strptime(post['attendance_date'], '%Y-%m-%d')
year = date.strftime('%Y')
month = date.strftime('%m')
day = date.strftime('%d')
_class = Room.objects.get(id=post['classIns'])
Attendance.objects.filter(attendance_date__year=year, attendance_date__month=month,
attendance_date__day=day, classIns=_class).delete()
for student in post.getlist('student[]'):
type = post['type['+student+']']
studInstance = Student.objects.get(id=student)
att = Attendance(student=studInstance, type=type, classIns=_class,
attendance_date=post['attendance_date']).save()
resp['status'] = 'success'
messages.success(request, "Attendance has been saved successfully.")
return HttpResponse(json.dumps(resp), content_type="application/json")
Jquery used
<script>
$(document).ready(function () {
$('table td, table th').addClass('px-2 py-1')
$('#data-form').change(function() {
location.href = "{% url 'attendance-page' class.pk %}/" + $(this).val()
})
$('#attendance-form').submit(function (e) {
e.preventDefault()
var _this = $(this)
$('.err-msg').remove();
var el = $('<div>')
el.addClass("alert alert-danger err-msg")
el.hide()
start_loader()
$.ajax({
url: "{% url 'save-attendance' %}",
data: $(this).serialize(),
method: 'POST',
type: 'POST',
dataType: 'json',
error: err => {
console.log(err)
alert("An error occured ", 'error');
end_loader();
},
success: function (resp) {
if (typeof resp == 'object' && resp.status == 'success') {
el.removeClass("alert alert-danger err-msg ")
location.reload()
} else if (resp.status == 'failed' && !!resp.msg) {
el.html(resp.msg)
} else {
el.text("An error occured ", 'error');
end_loader();
console.err(resp)
}
_this.prepend(el)
el.show('slow')
$("html, body, .modal ").scrollTop(0);
end_loader()
}
})
})
})
</script>
attendance template
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div class="card card-default rounded-0 shadow ">
<div class="card-header">
<div class="d-flex w-100 align-items-center justify-content-between">
<h4 class="card-title fw-bold">Class Attendance Management</h4>
<div class="tools">
</div>
</div>
</div>
<div class="card-body">
<form id="attendance-form">
{% csrf_token %}
<input type="hidden" name="classIns" value="{{ class.pk }}">
<div class="container-fluid">
<fieldset>
<legend>Class Details</legend>
<div class="row">
<!-- <div class="col-md-6">
<div class="d-flex w-100">
<div class="col-auto pe-2 text-muted">Department:</div>
<div class="col-auto flex-shrink-1 flex-grow-1">
<p class="m-0 fw-bold">{{ class.assigned_faculty.department }}</p>
</div>
</div>
</div> -->
<div class="col-md-6">
<div class="d-flex w-100">
<div class="col-auto pe-2 text-muted">School Year:</div>
<div class="col-auto flex-shrink-1 flex-grow-1">
<p class="m-0 fw-bold">{{ class.school_year }}</p>
</div>
</div>
</div>
<div class="col-md-6">
<div class="d-flex w-100">
<div class="col-auto pe-2 text-muted">Level:</div>
<div class="col-auto flex-shrink-1 flex-grow-1">
<p class="m-0 fw-bold">{{ class.level }}</p>
</div>
</div>
</div>
<div class="col-md-6">
<div class="d-flex w-100">
<div class="col-auto pe-2 text-muted">Name:</div>
<div class="col-auto flex-shrink-1 flex-grow-1">
<p class="m-0 fw-bold">{{ class.name }}</p>
</div>
</div>
</div>
<div class="col-md-6">
<div class="d-flex w-100">
<div class="col-auto pe-2 text-muted">Faculty:</div>
<div class="col-auto flex-shrink-1 flex-grow-1">
<p class="m-0 fw-bold">{{ class.form_teacher}}</p>
</div>
</div>
</div>
</div>
</fieldset>
<hr>
<fieldset>
<legend>Date of Class</legend>
<div class="row">
<div class="col-lg-4 col-md-6 col-sm-12">
<input id="data-form" type="date" name="attendance_date" value="{% if date %}{{ date }}{% endif %}"class="form-control form-control-lg rounded-0" required>
</div>
</div>
</fieldset>
{% if date %}
<fieldset>
<legend>Attendance List</legend>
<table class="table tables-bordered" id="student-list">
<colgroup>
<col width="5%">
<col width="25%">
<col width="25%">
<col width="15%">
<col width="15%">
<col width="15%">
</colgroup>
<thead>
<tr>
<th class="text-ceter">#</th>
<th class="text-ceter">Student Code</th>
<th class="text-ceter">Student Name</th>
<th class="text-ceter">Total Tardy</th>
<th class="text-ceter">Total Absent</th>
<th class="text-ceter">Total Present</th>
</tr>
</thead>
<tbody>
{% for student in att_data %}
<tr class="">
<td class="text-center">{{ forloop.counter }}</td>
<td>{{ student.data.student_code }}</td>
<td>{{ student.data.first_name }} {{ student.data.middle_name }} {{ student.data.last_name }}</td>
<td class="text-center">
<input type="hidden" name="student[]" value="{{ student.data.pk }}">
<input type="radio" class="btn-check" name="type[{{ student.data.pk }}]" value="1"
id="btnradio-{{student.data.pk}}" {% if student.type == '1' %} checked="checked" {% endif %}
autocomplete="off" required>
<label class="btn btn-outline-primary btn-sm px-1 py-0" for="btnradio-{{student.data.pk}}"><i
class="fa fa-check text-light"></i></label>
</td>
<td class="text-center">
<input type="radio" class="btn-check" name="type[{{ student.data.pk }}]" value="2"
id="btnradio-2-{{ student.data.pk }}" {% if student.type == '2' %} checked="checked" {% endif %}
autocomplete="off">
<label class="btn btn-outline-warning btn-sm px-1 py-0" for="btnradio-2-{{ student.data.pk }}"><i
class="fa fa-check text-light"></label>
</td>
<td class="text-center">
<input type="radio" class="btn-check" name="type[{{ student.data.pk }}]" value="3"
id="btnradio-3-{{ student.data.pk }}" {% if student.type == '3' %} checked="checked" {% endif %}
autocomplete="off">
<label class="btn btn-outline-danger btn-sm px-1 py-0" for="btnradio-3-{{ student.data.pk }}"><i
class="fa fa-check text-light"></label>
</td>
</tr>
{% endfor %}
</tbody>
</table>
<div class="clear-fix py-3"></div>
<center>
<button class="btn btn-sm btn-primary rounded-0 bg-gradient"><i class="fa fa-save"></i>
Save</button>
</center>
</fieldset>
{% endif %}
</div>
</form>
</div>
</div>
</div>
It's this line location.href = "{% url 'attendance-page' class.pk %}/" + $(this).val()
class.pk is not defined so it tries to call url with 0 arguments while it needs only one.

Laravel 8 Livewire refresh data after click|model events

I'm trying to create a simple table list view with laravel and livewire component. I can show the component but when I fire an event (change, wiremodel, click) the dataset is not updating, for example, I have an input text to filter my table, when I write on input the request is firing and component is getting it but component nor re-render with the new information
That's my full view
<header class="header py-6">
<div class="flex justify-between">
<h2 class="font-bold text-2xl text-blue-dark leading-tight">
{{ __('messages.Seizures') }}
</h2>
<div class="flex items-end">
<div class="cursor-pointer">
<i class="fas fa-plus-circle text-blue-light text-3xl"></i>
</div>
<div class="pl-8 flex items-center">
<i class="fas fa-filter text-blue-light text-lg"></i>
<input type="text" name="search" id="search-seizure" class="border border-blue-light rounded-full h-8 ml-1 px-4 text-blue-light" wire:model="filter">
</div>
<div class="pl-8 cursor-pointer" wire:click.prevent="toggleTrash()">
#if( $trash )
<i class="fas fa-trash text-blue-light text-xl"></i><i class="fas fa-toggle-on text-blue-light text-xl"></i>
#else
<i class="fas fa-trash text-gray-400 text-xl"></i><i class="fas fa-toggle-off text-xl text-gray-400"></i>
#endif
</div>
</div>
</div>
</header>
<div class="seizure-page">
<table class="table">
<thead>
<tr>
<th>#sortablelink('date', __('messages.Date'), [], ['class' => 'pr-2'])</th>
<th>{{ __('messages.Duration') }}</th>
<th>#sortablelink('location', __('messages.Location'), [], ['class' => 'pr-2'])</th>
<th>{{ __('messages.Notes') }}</th>
<th width="100px" class="text-right">{{ __('messages.Actions') }}</th>
</tr>
</thead>
<tbody>
#foreach($seizures as $seizure)
<tr class="cursor-pointer">
<td>{{ $seizure->date }}</td>
<td class="w-64">{{ $seizure->duration }}</td>
<td>{{ $seizure->location }}</td>
<td class="truncate-cell">{{ $seizure->note }} </td>
<td class="end">
<div class="flex justify-end">
<button wire:click="" class="btn btn-danger btn-sm px-1"><i class="fas fa-info"></i></button>
<button wire:click="edit({{ $seizure }})" class="btn btn-primary btn-sm px-1"><i class="fas fa-pen"></i></button>
<button wire:click="delete({{ $seizure }})" class="btn btn-danger btn-sm px-1"><i class="fas fa-trash text-warm-red"></i></button>
</div>
</td>
</tr>
#endforeach
</tbody>
</table>
<div class="flex justify-center pt-4">
{{ $seizures->links('vendor.pagination.neurons-unchained') }}
</div>
</div>
And this is the component logic
<?php
namespace App\Http\Livewire;
use Livewire\Component;
use App\Models\Seizure;
use Carbon\Carbon;
use Livewire\WithPagination;
class Seizures extends Component
{
use WithPagination;
public $trash = false;
public $filter;
public function render()
{
//TODO: Get paginate number from user settings
$seizures = Seizure::sortable(['date' => 'desc'])
->whereNull('deleted_at')
->where('note', 'like', '%' . $this->filter . '%')
->paginate(10);
if( $this->trash) {
$seizures = Seizure::sortable(['date' => 'desc'])
->whereNotNull('deleted_at')
->where('note', 'like', '%' . $this->filter . '%')
->paginate(10);
}
return view('livewire.seizure.index')
->with('seizures', $seizures->appends(\Request::except('page')))
->layout('layouts.dashboard');
}
public function delete(Seizure $seizure) {
$seizure->deleted_at = Carbon::now();
$seizure->save();
$this->gotoPage(1);
}
public function toggleTrash () {
$this->trash = !$this->trash;
}
}
The toggle button for show elements in trash has same problem
Many thanks

Updata table html EJS + Nodejs + Expressjs

I have an application nodejs + expressjs + ejs.
I am building a history search screen, my question is how to update my ejs html table with the values ​​returned in the response.
Uploading the screen with the values ​​is working, but when I enter the filters and search, I would like to update my table.
In the example below is how to use to load the html the first time with the data of the query, I would like to fill in an initial and final date and click on searching and updating the html.
EJS HTML
<div class="row">
<div class="col-md-2">
<div class="form-group">
<label for="dataPrimayID">Date Primary</label>
<input type="text" class="form-control datepickerDefault" id="dataPrimayID" name="dataPrimary" maxlength="250">
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label for="dataFinalID">Date Final</label>
<input type="text" class="form-control datepickerDefault" id="dataFinalID" name="dataFinal" maxlength="250">
</div>
</div>
<div class="col-md-2">
<a id="btnSearch" class="btn btn-primary">Search</a>
</div>
</div>
<div class="row">
<div class="table-responsive col-md-12">
<table id="dataTableHistoricoID" class="table table-striped" cellspacing="0" cellpadding="0">
<thead>
<tr>
<th>Name</th>
<th>LastName</th>
</tr>
</thead>
<tbody>
<% if(data.length > 0){ %>
<% for ( var i = 0 ; i < data.length ; i++){ %>
<tr>
<td>
<%= data[i].name%>
</td>
<td>
<%= data[i].lastname%>
</td>
</tr>
<% } %>
<% } %>
</tbody>
</table>
</div>
</div>
ROUTER
var express = require('express');
var router = express.Router();
var historyController = require('../controllers/history-controller');
router.get('/find', historyController.findHistory);
module.exports = router;
Controller
db.query(sql, function (err, rows) {
if (err) {
var message = err.message;
console.log(message);
return res.status(500).send(message);
}else {
var data = rows;
res.render('history/search-history', {data: data});
}
});
EJS is static after compiling, you can't change it on backend-side. There are two ways of it.
Refreshing the page every time you want to render new content.
Implement client-side JS code that will handle api requests and render new elements.
For example, using Jquery:
$.post(url, (result) => {
let data = JSON.parse(result);
let innerHTML = '';
for (let item of data) {
innerHTML += `<tr>
<td>
${item.name}
</td>
<td>
${item.lastname}
</td>
</tr>`;
}
$('#dataTableHistoricoID tbody').html(innerHTML)
};

Angular2 dependent dropdown based on selected value

Here am trying to append a dependent drop down based on value drop down (you can see in my HTML code for value drop down).I have wrote a onchage method to get appear dependent dropdown in html.Here i have dependent drop down for only three(i.e, Services Performed, Products Sold, Gross Retail) selected values of my values dropdown. Now am getting the dependent dropdowns, but when i have change the another drop down i.e, 2nd or 3rd ...etc dropdown ,then the previous drop down is getting disappear and latest changed dropdown value is getting appear.
so, please help me to solve it.
my HTML code is
<table class="table table-bordered-light">
<tbody>
<tr class="grey_th">
<td>Step</td>
<td>Action</td>
<td>Value</td>
<td>Number</td>
<td>Sample Calculation</td>
</tr>
<tr *ngFor="let row of rows; let i = 'index'">
<td [innerHTML]="row.step"></td>
<td>
<select [class.disabled]="i==0" [(ngModel)]="row.operator" name="action" style="width: 100%">
<option *ngFor="let actions of actionsStaticData; let i='index'" value="{{actions.id}}" id="actions{{i}}">{{actions.action}}</option>
</select>
</td>
<td>
<tr>
<td>
<div>
<!-- here i have wrote onchange method **onValueChange()** and passing i also along with the value -->
<
[(ngModel)]="row.operand" style="width: 100%" (change)="onValueChange($event.target.value, i)">
<option *ngFor="let values of valuesStaticData; let i='index'" value="{{values.value}}" id="values{{i}}">{{values.value}}</option>
<option value="-" disabled="disabled">-----</option>
<option *ngFor="let values of scalesData; let i='index'" value="{{values.Id}}" id="values{{i}}">{{values.Name}}</option>
</select>
</div>
</td>
<td>
<div class="ml-15" *ngIf='rowLength == i'>
<select [(ngModel)]="row.operandSubOption" style="width: 100%">
<option *ngFor="let values of servicesList; let i='index'" value="{{values.value}}" id="values{{i}}">{{values.Name}}</option>
</select>
</div>
</td>
</tr>
</td>
<td>
<input type="text" [(ngModel)]="row.numeral">
</td>
<td> {{row.result}}{{toFix}}</td>
<td>
<a style="color: #000;" (click)="addRows()" *ngIf='showPlus == true'>
<span class="f-plus">
<i class="fa fa-plus" aria-hidden="true"></i>
</span>
</a>
<a *ngIf='showPlus == false'>
<!-- <span class="del">
<i class="fa fa-plus disable" aria-hidden="true"></i>
</span> -->
</a>
<a (click)="deleteFieldValue(row, i)" *ngIf='hideDelete==true' data-toggle="tooltip" data-placement="top" title="Remove">
<span class="f-minus">
<i class="fa fa-trash-o" aria-hidden="true"></i>
</span>
</a>
</td>
</tr>
</tbody>
</table>
my typesript code is
onValueChange(value, i) {
if (value === 'Services Performed') {
this.rowLength = i;
this.servicesList = '';
this.setupCompMethodService.getServices()
.subscribe(data => {
this.servicesList = data['result'];
this.rows[i]['operandSubOption'] = this.servicesList[0].Name;
});
}
if (value === 'Products Sold') {
this.rowLength = i;
this.servicesList = '';
this.setupCompMethodService.getInventoryGroupData()
.subscribe(data => {
this.servicesList = data['result'];
this.rows[i]['operandSubOption'] = this.servicesList[0].Name;
});``
}
if (value === 'Gross Retail') {
this.rowLength = i;
this.servicesList = '';
this.setupCompMethodService.getProductLineDetails()
.subscribe(data => {
this.servicesList = data['result'];
this.rows[i]['operandSubOption'] = this.servicesList[0].Name;
});
}
}

how to insert multiple data fields in one string in mongodb nodejs

i am doing an invoice project using node.js in which i have to store multiple products in a string and my code is
the schema file
var mongoose = require('mongoose');
var autoIncrement = require('mongoose-auto-increment');
var invoiceSchema = mongoose.Schema({
date: String,
documentNo:Number,
vendorName:String,
pno:Number,
productName:String,
description:String,
quantity:Number,
costPrice :Number,
mrp:Number,
invoiceNo:Number,
advance:Number,
due:Number,
discount:Number,
Tax : String,
netTotal:Number,
size:String,
colour:String,
grandTotal:Number
},{collection:'invoice-data'});
var invoice = module.exports = mongoose.model('invoice',invoiceSchema);
now for routing
var product = require('../models/product');
var invoice= require('../models/invoice.js');
exports.addaInvoice=function(req, res) {
var date=req.body.date;
var invoiceNo=req.body.invoiceNo;
var vendorName = req.body.vname;
var pno = req.body.orderNo;
var productName = getElementById(req.body.productname);
var description = req.body.desc;
var colour = req.body.colour;
var size = req.body.size;
var quantity = req.body.quantity;
var costPrice = req.body.costPrice;
var mrp = req.body.mrp;
var amount=req.body.amount;
var discount=req.body.discount;
var discountvalue=req.body.discountvalue;
var netamount=req.body.netamount;
var advance = req.body.advance;
var due = req.body.due;
var Tax = req.body.Tax;
var netTotal = req.body.netTotal;
var subTotal = req.body.subTotal;
var grandTotal = req.body.grandTotal;
var newInvoice = new invoice({
date: date,
invoiceNo:invoiceNo,
vendorName:vendorName,
pno:pno,
productName:productName,
description:description,
colour:colour,
size:size,
quantity:quantity,
costPrice :costPrice,
amount:amount,
discount:discount,
discountvalue:discountvalue,
netamount:netamount,
mrp:mrp,
advance:advance,
due:due,
Tax :Tax,
netTotal:netTotal,
subTotal : subTotal,
grandTotal : grandTotal
});
newInvoice.save();
req.flash('success_msg',' purchase invoice added ')
res.redirect('/users/invoicedetails');
}
html code
<head>
<script type="text/javascript">
function calculate()
{
var quantity = document.getElementById('quantity');
var costprice = document.getElementById('costprice');
//var amount = document.getElementById('amount');
var result=quantity.VA*costprice.value;
//amount.value = result;
$("#amount").val(result);
}</script>
<SCRIPT language="javascript">
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for(var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[0].cells[i].innerHTML;
//alert(newcell.childNodes);
switch(newcell.childNodes[0].type) {
case "text":
newcell.childNodes[0].value = "";
break;
case "checkbox":
newcell.childNodes[0].checked = false;
break;
case "select-one":
newcell.childNodes[0].selectedIndex = 0;
break;
}
}
}
</SCRIPT>
</head>
<div class="form-group">
<label class="col-md-4 control-label" for="date">date</label>
<div class="col-md-8">
<input id="date" name="date" placeholder="date" class="form-control input-md" type="date">
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="invoiceNo">invoiceNo</label>
<div class="col-md-8">
<input id="invoiceNo" name="invoiceNo" placeholder="invoiceNo" class="form-control input-md" type="text">
</div>
</div>
<!-- Select Basic -->
<div class="form-group">
<label class="col-md-4 control-label" for="vendorname">Vendor name</label>
<div class="col-md-8">
<select id="vendorName" name="vendorName" class="form-control">
{{# each items }}
<option> {{ this.vendorName}}</option>
{{/each}}
</select>
</div>
</div>
</td>
</tr>
</table>
<INPUT type="button" value="Add Product " onclick="addRow('dataTable')" />
<table class="table table-hover" >
<thead>
<tr>
<td>productno</td>
<td>productName</td>
<td>size</td>
<td>colour</td>
<td>quantity</td>
<td>costprice</td>
<td>MRP</td>
<td>amount</td>
<td>discount%</td>
<td>discount value</td>
<td>net amount</td>
</tr>
</thead>
<TABLE id="dataTable" class="table table-hover" >
<TR>
<td>
<input id="orderNo" name="orderNo" placeholder="productno" class="form-control input-md" required="" type="text">
</td>
{{# each items }}
<option value="{{ this.productid}}"> {{ this.productname}}</option>
{{/each}}
</select>
</td>
<td>
<select id="size" name="size" class="form-control-md">
{{# each items }}
<option > {{ this.size}}</option>
{{/each}}
</select>
<!-- Text input-->
</td>
<td>
<select id="colour" name="colour" class="form-control-md">
{{# each items }}
<option > {{ this.colour}}</option>
{{/each}}
</select>
</td>
<td>
<input id="quantity" name="quantity" placeholder="Quantity" class="form-control " type="text">
</td>
<td>
<input id="costPrice" name="costPrice" placeholder="costPrice" class="form-control" type="text" onChange="calculate()">
</td>
<!-- Text input-->
<td>
<input id="mrp" name="mrp" placeholder="mrp" class="form-control" type="text">
</td>
<td>
<td>
<input id="amount" name="amount" placeholder="amount" class="form-control" >
</td>
<td>
<input id="discount" name="discount" placeholder="discount%" class="form-control"type="text">
</td>
<td>
<input id="discountvalue" name="discountvalue" placeholder="discountvalue" class="form-control"type="text">
</td>
<td>
<input id="netamount" name="netamount" placeholder="netamount" class="form-control"type="text">
</td>
</tr>
</tbody>
</table>
<table>
<!-- Text input-->
<td>
<label class="col-md-8 control-label" for="advance">Advance</label>
<div class="col-md-4">
<input id="advance" name="advance" placeholder="Advance" class="form-control input-md" type="text">
</div>
<div class="form-group">
<label class="col-md-8 control-label" for="Tax">Tax</label>
<div class="col-md-4">
<select id="Tax" name="Tax" class="form-control">
<option value="14.50">14.10</option>
<option value="12.50">12.50</option>
</select>
</div>
</div>
</td>
</table>
</table>
<label class="col-md-8 control-label" for="netTotal">netTotal</label>
<div class="col-md-4">
<input id="netTotal" name="netTotal" placeholder="netTotal" class="form-control input-md" type="text">
</div>
<label class="col-md-8 control-label" for="subTotal">SubTotal</label>
<div class="col-md-4">
<input id="subTotal" name="subTotal" placeholder="subTotal" class="form-control input-md" type="text">
<label class="col-md-8 control-label" for="grandTotal">grandTotal</label>
<div class="col-md-4">
<input id="grandTotal" name="grandTotal" placeholder="grandTotal" class="form-control input-md" type="text">
<label class="col-md-8 control-label" for="due">due</label>
<div class="col-md-4" align="left">
<input id="due" name="due" placeholder="due" class="form-control input-md" type="text">
</div>
<!-- Button -->
<div class="form-group" align="bottom">
<label class="col-md-4 control-label" for="vadd"></label>
<div class="col-md-4">
<button id="iadd" name="iadd" class="btn btn-primary">ADD</button>
</div>
</div>
</fieldset>
</form>
</div>
</div>
this is my html code in it the script is for cloning of the table for addingg a row in the tablle for multiple product entry
now this will work for one product if i have 2 or more products
how can i save these three products in a same document as like purchase invoice
If you are using bodyParser middleware, then you can pass an array of values from the client-side.
On client-side you might need to name your input elements as follows
<input name="products[#{1}][productname]" type="text">
<input name="products[#{1}][description]" type="text">
<input name="products[#{2}][productname]" type="text">
<input name="products[#{2}][description]" type="text">
and so on
This way your request body will have
{
"products": {
"1": {
"product name": "name goes here ",
"description": "desc goes here "
},
"2": {
"product name": "name goes here",
"description": "desc goes here"
}
}
}
You can iterate through that and get the values in your router as
var products = Array.prototype.slice.call(request.body.products);
for (var i = 0; i < messages.length; i++) {
var newInvoice = new invoice({
productName: products[i].productname,
description: products[i].description
});
newInvoice.save();
});
First you need to change your invoice schema to add multiple products in it. You need to add a array of product sub documents, I have added a sample schema below
// Product Schema
var ProductSchema = mongoose.Schema({
pno:Number,
productName:String,
description:String,
quantity:Number,
costPrice :Number,
mrp:Number,
size:String,
colour:String,
});
var invoiceSchema = mongoose.Schema({
date: String,
documentNo:Number,
vendorName:String,
products: [ProductSchema],
invoiceNo:Number,
advance:Number,
due:Number,
discount:Number,
Tax : String,
netTotal:Number,
grandTotal:Number
},{collection:'invoice-data'});
I haven't checked this code syntactically, I am just giving you an idea how to create schema if you want to store multiple sub documents in a single document.
And in your node.js code also, you need to save an array of products
var productArr = [];
var temProduct = {};
temProduct.pno= pno;
temProduct.productName= productName;
temProduct.description= description;
temProduct.colour= colour;
temProduct.size= size;
temProduct.quantity= quantity;
temProduct.costPrice = costPrice;
temProduct.amount = amount;
temProduct. = mrp;
productArr.push(temProduct);
var newInvoice = new invoice({
date: date,
invoiceNo:invoiceNo,
vendorName:vendorName,
products:productArr,
advance:advance,
due:due,
Tax :Tax,
netTotal:netTotal,
subTotal : subTotal,
grandTotal : grandTotal
});
newInvoice.save(function(err, new_data) {
if(err) {
// Handle error here, if any come
} else {
req.flash('success_msg',' purchase invoice added ')
res.redirect('/users/invoicedetails');
}
});
You can push as mush as products you want in productArr, then add it in invoice object and then save it.
I am mentioning again, that above code is not good to run directly, you need to do few changes, but it will give you an idea how to do it.

Resources