input checkbox add duplicate data in third cycle on checked - javascript

I write down a function which is bulk deletion on table. There is a table with checkbox on every rows, if some one select checkboxs then click on delete button its shows a confirmation modal, if it is close them modal then no action occurs.
In my case when I checked the boxes modal shows correct selected data, and if I then unchecked their is no problem, problem occurs when third time checked it populate previous unchecked data in modal. means checked -> unchecked -> checked.
let newTableData = "";
$('.btn-delete-employees-table-danger').hide();
let modalValue = null;
let selectedID = null;
let selectedRow = ""
let counter = 0;
console.log($('.btndelete'));
$(document).on('click', '.btndelete', function(e) {
$('.btn-delete-employees-table-danger').show();
if ($(this).prop("checked") == true || this.checked) {
counter = counter + 1;
var id = $(this).closest('tr').data('id');
selectedRow = $(`.roww[data-id=${id}]`);
selectedID = $(this).closest('tr').attr('id');
$(this).closest('tr').addClass('deleteselectedrow')
if($(this).closest('tr').addClass('deleteselectedrow')) {
$('.counter-of-selected-emp-modal').html(`${counter} employees will be deleted`)
newTableData += `
<div class="card mt-3" id="emp-${selectedID}">
<div class="d-flex justify-content-between modal-row">
<div>
<h4>${selectedRow[0].cells[1].innerText}</h4>
<p class="light-small-grey-text">ID</p>
</div>
<div>
<h4>${selectedRow[0].cells[2].innerText}</h4>
<p class="light-small-grey-text">Emp Name</p>
</div>
<div>
<h4>${selectedRow[0].cells[3].innerText}</h4>
<p class="light-small-grey-text">Emp DOB</p>
</div>
<div>
<h4>${selectedRow[0].cells[4].innerText}</h4>
<p class="light-small-grey-text">Emp CNIC</p>
</div>
</div>
</div>
`
console.log(newTableData);
}
$('.data-in-modal').html(newTableData);
} else {
counter = counter - 1;
$('.counter-of-selected-emp-modal').html(`${counter} employees will be deleted`)
selectedID = $(this).closest('tr').attr('id');
console.log($(selectedRow[0].cells[0].childNodes[1].checked))
console.log($("#emp-"+selectedID));
$(this).prop('checked', false);
$("#emp-"+selectedID).remove();
$("#emp-"+selectedID).empty();
$(this).prop("checked") == false;
$("#emp-"+selectedID).addClass('d-none')
console.log($('.data-in-modal'));
console.log(newTableData);
}
if(counter == 0 ) {
$('.btn-delete-employees-table-danger').hide();
$('.data-in-modal').html("");
newTableData = '';
}
});
function getandsetdate() {
var date = new Date().toISOString('yyyy-mm-dd').split('T')[0];
var element = document.getElementById('date')
element.value = date
return date
}
// show confirmation modal
$('.shown-modal').on('click', function (e) {
var policy_date_elem = $('input[name="emp_policy_end"]')
policy_date_elem.val(getandsetdate())
policy_date_elem.css('border', '1px #ced4da solid')
$('#showsDependentModal').modal('show');
})
$('#btnDelteYes').click(function () {
$('.deleteselectedrow').remove();
console.log($('.deleteselectedrow'))
console.log($('.deleteselectedrow').prevObject[0]);
$('.btn-delete-employees-table-danger').hide();
newTableData = ""
$('#showsDependentModal').modal('hide');
});
$('.no-btn').click(function () {
$('tr').removeClass('deleteselectedrow')
$('#showsDependentModal').modal('hide');
})
<table class="table table-bordered sortable empy-table" id="table">
<thead class="">
<tr>
<th>
Select
</th>
<!-- <th>check</th> -->
<th>Emp ID</th>
<th>Employee Name</th>
<th>DOB</th>
<th>CNIC</th>
<th class="noExport">Details</th>
</tr>
</thead>
<tbody id="search-table" class="employees_body">
<!-- {% for employee in employees %}
<tr id="{{ employee.id }}" data-id="{{ forloop.counter }}" class="roww">
 <td>
<input class="btndelete" type="checkbox" name="employee_id" value="{{ employee.id }}" />
</td>
<td>
{{employee.id}}
</td>
<td>
{{employee.first_name}} {{employee.last_name}}
</td>
<td>
{{employee.date_of_birth}}
</td>
<td>
{{employee.cnic}}
</td>
<td class="noExport">
<a class="text-dark" href="{% url 'smartbenefits:employee_profile' employee.id %}">
<button class="button-detail"><span class="fa fa-info-circle"></span></button>
</a>
</td>
</tr>
{% endfor %} -->
</tbody>
</table>
</div>
</div>
</div>
</div>
<div class="modal hide fade" id="showsDependentModal" tabindex="-1" aria-labelledby="showssDependentModal" aria-hidden="true">
<div class="modal-dialog modal-lg modal-dialog-centered">
<div class="modal-content modal-secondary">
<div class="px-4 pt-5 w-100">
<div class="d-flex justify-content-between w-100">
<div class="">
<h4>Please confirm if you want to delete the below employees?</h4>
<p class="counter-of-selected-emp-modal"></p>
</div>
<i class="fa fa-window-close dependent-close-icons-modal no-btn" id="modal-dismiss" data-bs-dismiss="modal" aria-label="Close"></i>
</div>
</div>
<div class="modal-body">
<div class="data-in-modal ">
</div>
<div class="policy-end w-25 mt-3">
<!-- <input type="text" name="emp_policy_end" readonly vaule="" /> -->
<label class="date-detail" for="emp_policy_end">Policy End Date. <span
class="fa fa-info-circle"></span></label>
<span class="hover-message">Policy End date will be same as the current date. For further queries,
contact our ops team</span>
<input id="date" type="date" name="emp_policy_end" readonly />
</div>
</div>
<div class="modal-footer">
<button class="button-secondary active" id="btnDelteYes">Confirm</button>
</div>
</div>
</div>
</div>

Related

How can I pass the values of the relevant row into the modal when a click event occurs on a table?

When a click event occurs on a table, I want to pass the values of the relevant row into the modal. I wrote a code like this, but the values of the top row are always passed into the modal. What I want to do is to show the values in the row I clicked in the modal. How can I provide this?
my table codes here:
<table class="table align-middle" id="customerTable">
<thead class="table-light">
<tr>
<th class="sort" data-sort="name">Name Surname</th>
<th class="sort" data-sort="company_name">Phone Number</th>
<th class="sort" data-sort="leads_score">Note</th>
<th class="sort" data-sort="phone">Status</th>
<th class="sort" data-sort="location">Personal Name</th>
<th class="sort" data-sort="tags">Data Name</th>
<th class="sort" data-sort="action">Edit</th>
</tr>
</thead>
<tbody class="list form-check-all">
{% for x in model %}
<tr>
<td class="table-namesurname">{{x.name}}</td>
<td class="table-phonenumber">{{x.phonenumber}}</td>
<td class="table-note">{{x.note}}</td>
<td class="table-status">{{x.status}}</td>
<td class="table-callname">{{x.callname}}</td>
<td class="table-dataname">{{x.dataname}}</td>
<td>
<ul class="list-inline hstack gap-2 mb-0">
<li class="list-inline-item" data-bs-toggle="tooltip" data-bs-trigger="hover" data-bs-placement="top" title="Edit">
<a class="edit-item-btn" id="call-button" href="#showModal" data-bs-toggle="modal" data-id="{{x.id}}"><i class="ri-phone-line fs-16"></i></a> <!-- Here is the edit button -->
</li>
</ul>
</td>
</tr>
{% endfor %}
</tbody>
</table>
my modal here
<div class="modal fade" id="showModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-header bg-light p-3">
<h5 class="modal-title" id="exampleModalLabel"></h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close" id="close-modal"></button>
</div>
<form action="">
<div class="modal-body">
<input type="hidden" id="id-field" />
<div class="row g-3">
<div class="col-lg-12">
<div>
<label for="company_name-field" class="form-label">Name Surname</label>
<input type="text" id="call-name-surname" class="form-control" placeholder="Enter company name" value="" required />
</div>
</div>
<div class="col-lg-12">
<div>
<label for="company_name-field" class="form-label">Phone Number</label>
<input type="email" id="call-phone-number" class="form-control" placeholder="Enter company name" value="" required />
</div>
</div>
<!--end col-->
<div class="col-lg-12">
<div>
<label for="leads_score-field" class="form-label">Note</label>
<input type="text" id="call-note-field" class="form-control" placeholder="Enter lead score" value="" required />
</div>
</div>
<!--end col-->
<div class="col-lg-12">
<div>
<label for="phone-field" class="form-label">Status</label>
<input type="text" id="call-status-field" class="form-control" placeholder="Enter phone no" value="" required />
</div>
</div>
<div class="col-lg-12">
<div>
<label for="phone-field" class="form-label">Personal Name</label>
<input type="text" id="call-persnoel-name" class="form-control" placeholder="Enter phone no" value="" required />
</div>
</div>
</div>
</div>
<div class="modal-footer">
<div class="hstack gap-2 justify-content-end">
<button type="button" class="btn btn-light" data-bs-dismiss="modal">Kapat</button>
<button type="submit" class="btn btn-success" id="add-btn">Kaydet</button>
</div>
</div>
</form>
</div>
</div>
</div>
and the my script codes
<script type="text/javascript">
$(document).ready(function () {
$("#call-button").click(function() {
var nameSurname = $(this).closest('tr').find('.table-namesurname').text();
var phoneNumber = $(this).closest('tr').find('.table-phonenumber').text();
var note = $(this).closest('tr').find('.table-note').text();
var status = $(this).closest('tr').find('.table-status').text();
var callName = $(this).closest('tr').find('.table-callname').text();
var dataName = $(this).closest('tr').find('.table-dataname').text();
$("#call-name-surname").val(nameSurname)
$("#call-phone-number").val(phoneNumber)
$("#call-note-field").val(note)
$("#call-status-field").val(status)
$("call-persnoel-name").val(callName)
});
});
</script>
console output
Gökan 905387532589 <empty string> Aranmadı ece datatest
The problem here is that the values of the clicked element in the table are not coming. Whichever I click, the values of the element at the top of the table are displayed. How can I solve this problem?
HTML id attribute should be unique, adding multiple elements with the same id, when you select, you will only get the first element that has this id, you need to select the rows by class, you have edit-item-btn class for the button.
<script type="text/javascript">
$(document).ready(function () {
$(".edit-item-btn").click(function() {
var nameSurname = $(this).closest('tr').find('.table-namesurname').text();
var phoneNumber = $(this).closest('tr').find('.table-phonenumber').text();
var note = $(this).closest('tr').find('.table-note').text();
var status = $(this).closest('tr').find('.table-status').text();
var callName = $(this).closest('tr').find('.table-callname').text();
var dataName = $(this).closest('tr').find('.table-dataname').text();
$("#call-name-surname").val(nameSurname)
$("#call-phone-number").val(phoneNumber)
$("#call-note-field").val(note)
$("#call-status-field").val(status)
$("call-persnoel-name").val(callName)
});
});

Javascript function works only on the first table row inside my foreach laravel loop

I am using a javascript functions to input a number and automatically display the result after calculation inside a boostrap modal.
If click the request button at the first row, javascript functions work well. But when I click on the request button on the second row and succeeding rows, it doesn't function.
I am not really sure if the problem is the data inside the modal or the data outside the modal
I tried to getElementsByClassName instead of ID but it still not working.
<script>
function mult(value) { // === calculate the profit and the total amount due === //
var x = value * 15 / 100;
var y = parseFloat(x)+parseInt(value);
document.getElementById("profit").value = x;
document.getElementById("total").value = y;
}
</script>
<table id="table1">
<thead>
<tr>
<th>#</th>
<th>Full Name</th>
<th>Requests</th>
</tr>
</thead>
<tbody>
#foreach($Clients as $Client)
<tr id="foreach-row">
<td>{{ $Client->full_name }}</td>
<td>
<div class="buttons">
<a class="btn icon btn-secondary" data-toggle="modal"
data-target="#LoanRequestModel-{{ $Client->id }}">
Request
</a>
</div>
</td>
</tr>
{{-- =========== MODEL - NEW REQUEST ===============--}}
<div class="modal" id="LoanRequestModel-{{ $Client->id }}" tabindex="-1" role="dialog"
aria-labelledby="exampleModalLongTitle" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title"><b>REQUEST</b></h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<i data-feather="x"></i>
</button>
</div>
<div class="modal-body">
<form action="{{ route('finance.storeRequest', $Client->id) }}" method="post"
class="loanrequest_form" enctype="multipart/form-data">
{{ csrf_field() }}
<label>Full name</label>
<div class="form-group">
<input type="text" name="creditor_full_name"
class="form-control" value="{{ $Client->full_name }}" >
</div>
<div>
<label>Amount</label>
<div class="form-group">
<input type="number" name="loan_amount"
class="form-control" onkeyup="mult(this.value);" >
</div>
</div>
<div class="row">
<div class="col-md-5">
<label>Interest Rate</label>
<div class="input-group mb-3">
<label class="input-group-text" for="inputGroupSelect01">Choose</label>
<select class="form-select rate"name="interest_rate" >
<option value="15" selected>15%</option>
<option value="20">20%</option>
</select>
</div>
</div>
<div class="col-md-7">
<label>Profit</label>
<div class="input-group mb-3">
<input type="text" id="profit" class="form-control" name="profit"
aria-label="Amount">
</div>
</div>
</div>
<div class="row">
<label>Total Amount due</label>
<div class="input-group mb-3">
<input type="text" id="total" class="form-control" name="amount_due"
aria-label="Amount">
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-outline-secondary ml-1" >
<i class="bx bx-check d-block d-sm-none"></i>
<span class="d-none d-sm-block">Submit</span>
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
#endforeach
</tbody>
</table>
The problem - as others have said above - is that whilst you are making the ID of each modal unique using :
id="LoanRequestModel-{{ $Client->id }}"
within your loop, when generating each modal, you are using fields which have non-unique IDs :
type="text" id="profit"
type="text" id="total"
What you would be better off is making those IDs non-unique, in the same way that you did with the modal ID :
type="text" id="profit-{{ $Client->id }}"
type="text" id="total-{{ $Client->id }}"
and add IDs to the fields which you will need to use in your script that does not presently have one :
type="number" id="loan_amount-{{ $Client->id}}" name="loan_amount"
Then, when you trigger the javascript on keyup here :
onkeyup="mult(this.value);"
rather than pass the value of the field, pass the client ID :
onkeyup="mult({{ $Client->id);"
Then you just need to adjust your javascript (because it's no longer being passed the loan_amount) so that it first gets the loan_amount, then the other bits and pieces it needs, and finally returns them to the right place :
<script>
function mult(id) { // === this is now receiving the ID, not a value so first we need to get the value for the relevant field *emphasized text*== //
var value = document.getElementById("loan_amount-" + id).value
var x = value * 15 / 100;
var y = parseFloat(x)+parseInt(value);
document.getElementById("profit" + id).value = x;
document.getElementById("total" + id).value = y;
}
</script>

Join Multiple tables : Edit and Update an Item from a table list to a modal in asp.net mvc

I'm new to ASP.NET MVC and I'm having trouble editing an item and showing it in a modal form and updating it in the database. The data is not showing in a modal. The data is coming from different tables in the database.
Expected output: show the list in a single view(table) and edit a selected item from the list (modal) and update it.
Here's my code:
AdminController:
public JsonResult EditItem(int? itemID)
{
var id = db.Items.Where(i => i.ItemID == itemID).FirstOrDefault();
List<Item> itemList = db.Items.ToList();
List<ItemDetail> itemDetailList = db.ItemDetails.ToList();
List<ProductType> productTypeList = db.ProductTypes.ToList();
var details = from itm in itemList
join itmDetail in itemDetailList on itm.ItemID equals itmDetail.ItemID into ItemInfo
from itmDetail in ItemInfo.DefaultIfEmpty()
join product in productTypeList on itmDetail.ProductID equals product.ProductID into ProductInfo
from product in ProductInfo.DefaultIfEmpty()
where itm.ItemID.Equals(id)
select new TableCollection { Item = itm, ItemDetail = itmDetail, ProductType = product };
return Json(details, JsonRequestBehavior.AllowGet);
}
[HttpPost]
public ActionResult EditItem(Item item, ItemDetail details)
{
ItemDetail itmDetails = db.ItemDetails.Where(d => d.ItemID == item.ItemID).FirstOrDefault();
itmDetails.ItemID = details.ItemID;
db.SaveChanges();
return RedirectToAction("Inventory", "Admin");
}
InventoryList View:
#model IEnumerable<VetClinic.Models.Admin.TableCollection>
#if (Model != null)
{
<table id="inventory" class="table table-striped table-hover">
<thead class="thead-dark">
<tr>
<th>Product Type</th>
<th>Item Name</th>
<th># of Stock</th>
<th>Price</th>
<th>Action</th>
</tr>
</thead>
<tbody class="bg-light">
#foreach (var item in Model)
{
<tr id="row_#item.ItemDetail.ItemID">
<td>#item.ProductType.Name #item.ProductType.Type</td>
<td>#item.ItemDetail.ItemName</td>
<td>#item.ItemDetail.NumOfStock</td>
<td>#item.ItemDetail.Price</td>
<td>
<i class="fa fa-pencil" data-toggle="tooltip" title="Edit" style="color: blue;"></i>
</td>
</tr>
}
</tbody>
</table>
<div class="modal fade" id="EditItem" tabindex="-1" role="dialog" aria-labelledby="EditItem" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Edit Item</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
#using (Html.BeginForm("EditItem", "Admin", FormMethod.Post))
{
<input type="hidden" id="hiddenItemID" />
<div class="form-group row">
<div class="col-lg-3">
<label>Product Type:</label>
</div>
<div class="col-lg-4">
<input type="text" id="productType"/>
</div>
</div>
<div class="form-group row">
<div class="col-lg-2">
<label>Item Name:</label>
</div>
<div class="col-lg-3">
<input type="text" id="itemName" class="form-control" />
</div>
</div>
<div class="form-group row">
<div class="col-lg-5">
<label>Number of Stocks</label>
</div>
<div class="col-lg-2">
<input type="text" id="numOfStocks" class="form-control" />
</div>
</div>
<div class="form-group row">
<div class="col-lg-2">
<label>Price:</label>
</div>
<div class="col-lg-3">
<input type="text" id="price" class="form-control" />
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary">Update</button>
</div>
}
</div>
</div>
</div>
</div>
}
else
{
<i class="fa fa-info-circle"> </i>#ViewBag.EmptyList;
}
<script>
function EditItem(id) {
$.ajax({
url: "/Admin/EditItem/" + id,
type: "GET",
dataType: "json",
success: function (response) {
$("#hiddenItemID").val(response.ItemID);
$("#EditItem").modal("show");
}
});
return false;
}
</script>

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