Laravel - Get Row ID of selected Item - php

I'm new to Laravel. I want to check if there is an ID of the selected item and user from my form. Both these fields are in my item_assignments table. Whenever there is no ID found, it will create a new assignment and store it to the item_assignments table. This works but when there is an ID found, it should update the existing one by incrementing the count inputted.
Here is my view.
<form class="form-horizontal" method="post" action="{{url('item/assign')}}" enctype="multipart/form-data">
<input type="hidden" name="_token" value="{{ csrf_token() }}" >
<legend>Assign Item</legend>
<fieldset>
<input id="eid" name="id" type="hidden">
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="name">Item Name:</label>
<div class="col-md-6">
<input id="ename" name="name" type="text" class="form-control input-md" readonly>
</div>
</div>
<!-- Select Basic -->
<div class="form-group{{ $errors->has('user') ? ' has-error' : '' }}">
<label class="col-md-4 control-label" for="user">Assign to:</label>
<div class="col-md-6">
<select id="user" name="user" class="form-control">
<option value="0">Select a User</option>
#foreach($users as $user)
<option value="{{$user->id}}">{{$user->name}}</option>
#endforeach
</select>
#if ($errors->has('user'))
<span class="help-block">
<strong>{{ $errors->first('user') }}</strong>
</span>
#endif
</div>
</div>
<!-- Text input-->
<div class="form-group{{ $errors->has('count') ? ' has-error' : '' }}">
<label class="col-md-4 control-label" for="count">Item Count:</label>
<div class="col-md-6">
<input id="count" name="count" type="text" placeholder="Enter Item Count" class="form-control input-md">
#if ($errors->has('count'))
<span class="help-block">
<strong>{{ $errors->first('count') }}</strong>
</span>
#endif
</div>
</div>
<!-- Button (Double) -->
<div class="form-group">
<label class="col-md-5 control-label" for="submit"></label>
<div class="col-md-7">
<button id="submit" name="submit" class="btn btn-success">Assign</button>
</div>
</div>
</form>
This is my controller
// checks the ID of the selected item
$assign1 = ItemAssign::where("item_id", $req->id)->where('user_id', $req->user)->first();
// this works
if (!($assign1)) {
$assign = new ItemAssign();
$assign->user_id = $req->user;
$assign->item_id = $req->id;
$assign->item_count = $req->count;
$assign->balance = $req->count;
$assign->save();
}
// this is what I want to work
else {
$assign = ItemAssign::find($assign1);
$assign->item_count += $req->count;
$assign->balance += $req->count;
$assign->save();
}
// stores to user table
$user = User::find($req->user);
$user->received += $req->count;
$user->save();
// stores to item table
$item = Item::find($req->id);
$count = $item->item_count;
$item->assigned_count += $req->count;
$item->remaining = $count - $item->assigned_count;
$item->save();
return redirect('assignment');

If you already have an instance of ItemAssign stored in $assign1 you should be able to just update that one instead of using a find.
IE:
else {
$assign1->item_count += $req->count;
$assign1->balance += $req->count;
$assign1->update();
}

else {
$assign = ItemAssign::find($assign1);
$assign->item_count += $req->count;
$assign->balance += $req->count;
$assign->update();
}

Related

How to store an array as single row for each value in my database

the whole idea is that when a user click on checkbox and save, the form should be submitted with an array containing the checked values, and save them in the database as single row for each value. i don't know if this is possible but i'm sure you guys have a solution or can help me?
and here's my form:
<div class="">
<form style="width: 70%" method="POST" action="{{ URL('/admin/projects/services/save') }}"
enctype="multipart/form-data">
#csrf
<input type="hidden" name="id" id="id" value="{{ #$id }}">
<input type="hidden" name="projectid" id="projectid" value="{{ #$projectid }}">
<div class="row topSpacer">
<div class="col-3">
<p class="bold">Selected Services: <span class="red">*</span></p>
</div>
<div class="col-9">
<input type="text" id="selectedServices" name="selectedServices" value="" readonly>
</div>
</div>
<div class="row topSpacer">
<div class="col-3">
<p class="bold">Select a service: <span class="red">*</span></p>
</div>
<div class="col-9">
#foreach ($services as $service)
<input type="checkbox" name="service" value="<?php echo stripslashes($service->id); ?>">
<label for="service"><?php echo stripslashes($service->name); ?></label>
<br>
<hr>
#endforeach
#error('service')
<span class="text-danger">{{ $message }}</span>
#enderror
</div>
</div>
<div class="row topSpacerHuge">
<div class="col-12 textRight">
<button type="button"
onclick="window.location='{{ url('admin/projects/services/index/'.$projectid) }}'"
class="goBackBtn">Cancel</button>
<input class="saveBtn" id="saveBtn" type="submit" value="Save">
</div>
</div>
</form>
</div>
and my script to get checkboxes value:
<script>
$(function() {
$("input:checkbox[name='service']").click(function() {
$value = [];
$.each($("input:checkbox[name='service']:checked"), function() {
$value.push($(this).val());
$array = $value.join();
});
// console.log(value.join(", "));
$("#selectedServices").val($array);
})
});
</script>
for implementing checked values I recommend to use the select tag
and you can give A name attribute with [] and it will collect all of your data
for example , look at my project's file which I'm trying to collect name of some users :
<select name="users[]" id="example-with-maxHeight" class="multiselect-group" multiple >
#foreach($users as $user)
<option #if($user->average < $averageParticipate )class="alert-danger" #endif value="{{$user->id}}">{{$user->name}} - {{$user->average}}</option>
#endforeach
</select>
have attention to users[] in name attribute
now in your request you can access all of your checked items .
if we look at your code ,can be some thing like this :
<label for="service"><?php echo stripslashes($service->name); ?></label>
<select name="services[]" id="" class="multiselect-group" multiple >
#foreach($users as $user)
<option value = "{{$sevice->id}}"> <?php echo stripslashes($service->name); ?></option>
#endforeach
</select>
now in your controllers you can access them :
request->get('services');
it will give you back an array of selected items .
Notice that id attribute helps me to interact with my java script code
you can rename it to yourselves .

Auto calculate total value laravel livewire

i have a problem where the value isn't calculated.
I have function where the user able to update Weight/size and quantity(if the input isn't in readonly). When the user enter a new weight/size it will be auto-calculated in the Order Total. Apparently, there is a value already in the Order Total (since it is an update) so i want it to auto update the value in the order total when the user update the new input in weight/size or quantity.
pls click this picture
here is my updates.blade.php
<div class="col-sm-12 col-md-6" >
<div class="card">
<div class="card-body">
<div class="form-actions">
<div class="container" style="padding: 0;margin: 0;">
<div class="row">
<div class="col-sm-6" >
<span class="float-sm-left">
<h3 class="card-title">Update Order</h3>
</span>
</div>
</div>
</div>
</div>
</br>
<form action="" method="POST" >
#csrf
#method('PUT')
<div class="form-row">
<div class="col-md-4 mb-3">
<label for="validationTooltip01">Order ID</label>
<input type="text" class="form-control" wire:model="orderID" value="" readonly>
</div>
<div class="col-md-4 mb-3">
<label for="validationTooltip02">Order Date</label>
<input type="text" class="form-control" wire:model="orderDate" value="" readonly>
</div>
<div class="col-md-4 mb-3">
<label for="validationTooltipUsername">Order Status</label>
<input type="text" class="form-control" wire:model="orderStatus" value="" readonly>
</div>
</div>
<div class="form-row">
<div class="col-md-6 mb-3">
<label class="form-control-label" >Customer Phone Number</label>
<input type="text" name="" value="" class="form-control" maxlength="11" wire:model="custPhone" readonly>
</div>
<div class="col-md-6 mb-3">
<label class="form-control-label" >Customer Name</label>
<input type="text" name="" value="" class="form-control" maxlength="11" wire:model="custName" readonly>
</div>
</div>
<div class="form-row">
#foreach($serviceOrder as $o)
<div class="col-md-5 mb-3">
<label class="form-control-label" >Service {{ $loop->iteration }} </label>
<input type="text" wire:model="serviceOrder.{{ $loop->index }}.serv.serviceName" class="form-control " readonly>
</div>
<input type="hidden" wire:model="serviceOrder.{{ $loop->index }}.serv.servicePrice" class="form-control col-sm-1 mb-3" readonly>
<div class="col-md-3 mb-3">
<label class="form-control-label" >Weight/Size</label>
<input type="text" name="" value="" wire:model="serviceOrder.{{ $loop->index }}.weightsize" class="form-control">
</div>
<div class="col-md-3 mb-3">
<label class="form-control-label" >Quantity*opt</label>
<input type="text" name="" value="" wire:model="serviceOrder.{{ $loop->index }}.quantity" class="form-control" #if(!$serviceOrder[$loop->index]['quantity']) readonly #endif >
</div>
#endforeach
</div>
<label class="form-control-label" >Order Total RM</label>
<input type="number" wire:model="orderTotal" value="" class="form-control" readonly>
</br>
<div class="form-actions">
<div class="container" style="padding: 0;margin: 0;">
<div class="row">
<div class="col-sm-6" >
<span class="float-sm-left">
<a class="btn btn-primary" href="{{ route('orders.indexInProcess') }}"> Back</a>
</span>
</div>
<div class="col-sm-6">
<span class="float-sm-right">
<div class="text-right">
<button type="submit" class="btn btn-info mr-2">Update</button>
<button type="reset" class="btn btn-dark float-right">Reset</button>
</div>
</span>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
here is the livewire updates.php
<?php
namespace App\Http\Livewire;
use Livewire\Component;
use App\Customer;
use App\Service;
use App\Order;
use App\ServiceOrder;
class Updates extends Component
{
public $orders;
public $orderID;
public $orderDate;
public $orderStatus;
public $orderTotal;
public $custName;
public $custPhone;
public $serviceName;
public $servicePrice;
public $weightsize;
public $quantity;
public $serviceOrder;
public function mount($order,$so)
{
//$orders = Order::with('customer')->get();
//ServiceOrder::with('serv')->where('order_id', $order->id)->get();
$this->orderID = $order->id;
$this->orderDate = $order->orderDate;
$this->orderStatus = $order->orderStatus;
$this->orderTotal = $order->orderTotal;
$this->custPhone = $order->customer->custPhone;
$this->custName = $order->customer->custName;
$this->serviceOrder = $so->toArray();
//dd($this->serviceOrder);
//$so->serviceName,
//$so->weightsize,
//$so->quantity
}
public function render()
{
//$so = ServiceOrder::with('serv')->where('order_id', $order->id)->get();
return view('livewire.updates');
}
public function updatedInputs($name)
{
$array = explode('.', $name);
if ($array[1] == 'serviceName') {
$this->inputs[$array[0]]['servicePrice'] = $this->services->find($value)->servicePrice;
}
try {
$this->calculateTotal();
} catch (\Exception $e) {
}
}
// perform calculation here.
public function calculateTotal(){
$this->orderTotal = $this->orderTotal;
foreach ($this->serviceOrder as $item) {
if($item['quantity'] == ''){
$item['optQuantity']= 1;
$this->orderTotal += ($item['servicePrice'] * $item['weightsize']) * ($item['quantity']);
}else{
$this->orderTotal += $item['servicePrice'] * ($item['weightsize']) * ($item['quantity']);
}
//$this->total *= $item['optQuantity']; // * price;
}
}
}
please help me out here T.T
You can fire event from component (for example) and then register listener in class and call a method for updating total. Check documentation for that.
"Apparently, there is a value already in the Order Total (since it is an update) so i want it to auto update the value in the order total when the user update the new input in weight/size or quantity."
So, the problem is $orderTotal only update once? it doesn't update when user update new input?. Livewire should render everytime there is action or any input.
First of all, i advice u to check what happen when to your function when user update the new input with dd function.
public function calculateTotal(){
dd('is this func work?');
$this->orderTotal = $this->orderTotal;
foreach ($this->serviceOrder as $item) {
if($item['quantity'] == ''){
$item['optQuantity']= 1;
$this->orderTotal += ($item['servicePrice'] * $item['weightsize']) * ($item['quantity']);
}else{
$this->orderTotal += $item['servicePrice'] * ($item['weightsize']) * ($item['quantity']);
}
//$this->total *= $item['optQuantity']; // * price;
}
}
After you debug your function, maybe you already found the answer you looking for or you can come back and ask me anything. ^^

Laravel form validation doesn't work when in my controller declaring more databases

I declare a variable containing the database so that the blade can select, but when doing so, the validation does not work. Please help me. Thank you very much.
this is the variable I call in the database to use select in the blade.
public function new_department(){
//return view('admin.new-department');
$manage_faculties=DB::table('faculties')->orderBy('id','asc')->get();
$all_manage_faculties=view('admin.new-department')->with('manage_faculties', $manage_faculties);
return view('layouts.master')->with('admin.new-department', $all_manage_faculties);
}
Here is the validation I use in the insert information and database.
public function save_new_department(Request $request){
$data = [];
$data['department_name'] = $request->input('department_name');
$data['description'] = $request->input('description');
$data['faculty_id'] = $request->input('faculty_name');
if($request->isMethod('post')){
$validator = Validator::make($request->all(), [
'department_name' => 'required|min:3|max:100|unique:departments',
'description' => 'required|max:500',
]);
if ($validator->fails()) {
return back()->with('toast_error', $validator->messages()->all()[0])->withInput();
}
DB::table('departments')->insert($data);
return redirect('/admin/departments/new')->withSuccess('Post Created Successfully!');
}
}
display it in the blade
After entering data whether it is true or false, it is not possible to report an error on the screen.After entering data whether it is true or false, it is not possible to report an error on the screen.
<form class="mt-3"method="post" action="{{ url('admin/department/new-department') }}">
{{csrf_field()}}
<div class="modal-content">
<div class="modal-header bg-primary">
<h5 class="modal-title">Create a Department</h5>
</div>
<!--end of modal head-->
<div class="modal-body">
<div class="form-group row align-items-center" {{ $errors->get('name') ? 'has-error' : '' }}>
<label class="col-2">Department</label>
<input class="form-control col" type="text" placeholder="Department name" name="department_name" required/>
#foreach($errors->get('name') as $error)
<span class="help-block">{{ $error }}</span>
#endforeach
</div>
<div class="form-group row align-items-center">
<label class="col-2">Faculty</label>
<select name="faculty_name" class="form-control col" required>
<option value="" selected>Select a Faculty</option>
#foreach($manage_faculties as $key => $cate_pro)
<option value="{{$cate_pro->id}}">{{$cate_pro->faculty_name}}</option>
#endforeach
</select>
</div>
<div class="form-group row">
<label class="col-2">Description</label>
<textarea class="form-control col" rows="10" placeholder="Write something here..." name="description" required ></textarea>
</div>
</div>
<!--end of modal body-->
<div class="modal-footer">
<button role="button" class="btn btn-primary" type="submit">
Post
</button>
</div>
</div>
</form>
You can look here for displaying errors in Laravel.
Why did you put :
{{ $errors->get('name') ? 'has-error' : '' }}
inside a "div" like a attribute ?

Laravel - Edit product with polymorphic relation

I have a system where to user needs to be able to change a product. But the problem is, This product has a polymoprhic relation with theme. This is the build-up
Products
- ID
- productable_id (For instance "1")
- productable_type (Is either "App\Theme"or "App\Plugin")
- name (Just a name)
- description (Just a description)
- etc
Theme
- id (1)
- composer_package
Now I need the user to be able to change a product. Currently, I have it done like this in the controller
public function update(Request $request, $id)
{
$product = Product::find($id);
$product->fill($request->all());
$product->save();
return redirect('/products')->with('flash', $product->name . ' is succesvol bewerkt');
}
But since its a polymorphic relation I don't know how to change for example the "composer_package" that is associated with the selected product. Say, for instance, I want to change the product with the ID of 1. Then I want to also be able to change the composer_package with the id 1 because that one is associated with that selected product. Also, How can I change for instance, the type of product. The selected product is an App\Theme and I want to change that to App\Plugin. How can I achieve the above two things with this polymorphic relation
This is the form that is collecting the data. It's quite large
<div class="modal fade-scale" id="createProduct" tabindex="-1" role="dialog" aria-labelledby="IetsAnders" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="m-0">Product aanmaken</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-12">
<form method="POST" action="{{ route('addProduct') }}">
{{ csrf_field() }}
<div class="form-group">
<label for="name">Naam</label>
<input type="text" name="name" class="form-control" placeholder="Naam">
</div>
<div class="form-group">
<label for="description">Omschrijving</label>
<textarea name="description" id="" class="form-control" cols="30" rows="5"></textarea>
</div>
<div class="form-group">
<label for="productable_type">Product type</label>
<select name="type" id="productable_type" class="form-control">
<option selected>Kies een type...</option>
</select>
</div>
<div class="form-group">
<label for="price">Prijs</label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text" id="currency" style="background-color: white; border-right: none">€</span>
</div>
<input type="number" step="0.01" name="price" class="form-control" value="" aria-describedby="currency" style="border-left: none" placeholder="00.00">
</div>
</div>
<hr>
<div class="form-group">
<label for="period_id">Betalings periode</label>
<select name="period_id" id="" class="form-control">
<option selected>Kies een periode</option>
#foreach($plans as $plan)
<option>{{ $plan->name }}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for="periodically_price">Prijs per gekozen periode</label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text" id="currency" style="background-color: white; border-right: none">€</span>
</div>
<input type="text" name="periodically_price" class="form-control" value="" aria-describedby="currency" style="border-left: none" placeholder="00.00">
</div>
</div>
<div class="form-group mb-3">
<label for="thumbnail">Foto van product</label>
<input type="file" name="thumbnail" class="form-control">
</div>
<div class="form-group mb-3">
<label for="composer_package">Composer package</label>
<input type="text" name="composer_package" class="form-control" placeholder="Composer package">
</div>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Sluiten</button>
<button type="submit" class="btn btn-orange">Bewerken</button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
Thanks in advance!
EDIT
Product model
class Product extends Model
{
protected $fillable = [
'productable_type', 'productable_id', 'name', 'description', 'thumbnail', 'price', 'periodically_price', 'period_id'
];
public function productable()
{
return $this->morphTo();
}
public function order_items()
{
return $this->hasMany(Orderitems::class);
}
public function plan() {
return $this->belongsTo(Plan::class, 'period_id');
}
}
Theme Model
class Theme extends Model
{
protected $fillable = [
];
public function webshops()
{
return $this->hasMany(Webshop::class);
}
public function products()
{
return $this->morphMany(Product::class, 'productable');
}
}
Add composer_package to Theme::$fillable.
Adjust the HTML form: name="productable[composer_package]"
Then you can update the theme like this:
$product->productable->update($request->get('productable'))

getting total value after entering the values in the form and inserting into database using codeigniter

If i select Local Sales from dorpdown and enter DEF, GHI values then the sum of DEF,GHI should be displayed in total value or if i select Inter State,Stock Transfers from dropdown then if we enter ABC value that value should be displayed in total value or else if we select JOB WORK,EXEMPTED SALES from dropdown then the total value should be displayed as zero. The total value which ever we are getting that should be inserted into database.
Controller:
function addinvoice()
{
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<br /><span class="error"> ','</span>');
$this->form_validation->set_rules('user','User');
$this->form_validation->set_rules('freight_charges');
$this->form_validation->set_rules('abc');
$this->form_validation->set_rules('def');
$this->form_validation->set_rules('ghi');
$this->form_validation->set_rules('total');
if($this->form_validation->run()== FALSE)
{
$data['mainpage']='invoice';
$data['mode']='add';
$this->load->view('templates/template',$data);
}
else
{
$this -> invoice_model -> insert();
$this->flash->success('<h2> Details added Successfully!</h2>');
redirect('invoice');
}
}
Model:
function insert()
{
$data['total']=0;
$data['user'] = $this->input->post('user');
$data['ghi'] = ($this->input->post('ghi'))?$this->input->post('ghi'):0;
$data['abc'] = ($this->input->post('abc'))?$this->input->post('abc'):0;
$data['def'] = ($this->input->post('def'))?$this->input->post('def'):0;
$data['total'] = $data['ghi'] + $data['abc'] + $data['def'];
$data['freight_charges'] = $this->input->post('freight_charges');
$this->db->insert('invoice',$data);
}
View:
<script>
function showRequiredOption(cval)
{
if((cval=='interstate') || (cval == "stocktransfers"))
{
$('#ghi').hide();
$('#def').hide();
$('#abc').show();
}
else if ((cval=='exemptedsales') || (cval=="zeroratedsales") ||(cval=="jobwork"))
{
$('#ghi').hide();
$('#def').hide();
$('#abc').hide();
}
else
{
$('#abc').hide();
$('#ghi').show();
$('#def').show();
}
}
</script>
<div class="col-md-9 col-md-offset-2">
<div id="legend">
<legend class="">Profile Information</legend>
</div>
<form role="form" action="<?php echo site_url();?>invoice/addinvoice" method="post" class="form-horizontal" id="location" method="post" accept-charset="utf-8">
<div class="form-group">
<label class="control-label col-sm-2 " for="user">User</label>
<div class="col-sm-4 col-sm-offset-1">
<select id="user" name="user" onchange="showRequiredOption(this.value)">
<option value="employee">Local Sales</option>
<option value="interstate">Inter state</option>
<option value="stocktransfers">Stock transfers</option>
<option value="exemptedsales">Exempted Sales</option>
<option value="zeroratedcompany">Zero Rated Sales</option>
<option value="jobwork">Job Work</option>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2 " for="freight_charges">Freight Charges</label>
<div class="col-sm-4 col-sm-offset-1">
<input type="text" class="form-control" id="freight_charges" name="freight_charges" value="<?php echo set_value('freight_charges');?>" />
</div>
</div>
<div class="form-group" id="abc" style="display:none;">
<label class="control-label col-sm-2 " for="abc">ABC</label>
<div class="col-sm-4 col-sm-offset-1">
<input type="text" class="form-control" id="abc" name="abc" value="<?php echo set_value('abc');?>"/ >
</div>
</div>
<div class="form-group" id="def">
<label class="control-label col-sm-2 " for="def">DEF </label>
<div class="col-sm-4 col-sm-offset-1">
<input type="text" class="form-control" id="def" name="def" value="<?php echo set_value('def');?>"/ >
</div>
</div>
<div class="form-group" id="ghi">
<label class="control-label col-sm-2 " for="ghi">GHI</label>
<div class="col-sm-4 col-sm-offset-1">
<input type="text" class="form-control" id="ghi" name="ghi" value="<?php echo set_value('ghi');?>"/ >
</div>
</div>
<div class="form-group" id="cgst">
<label class="control-label col-sm-2 " for="total">Total</label>
<div class="col-sm-4 col-sm-offset-1">
<input type="text" class="form-control" name="total" >
</div>
</div>
<button id="submit" type="submit" class="btn" name="submit">Submit</button>
</form>
</div>
Whatever values i have selected from dropdown only those values to be inserted into database and the rest of the values should be inserted as zero in the database.
Actually i am not getting how to do these can anyone check this.Thanks in Advance.
you should check for posted values in your php code as:
$total = 0;
if($this->input->post('this')){
$total = $this->input->post('this');//value in total
}
if($this->input->post('this2')){
$total += $this->input->post('this2');//value in total
}
and at the end send $total value in db as well.
in short php if else tags you can set variables like;
$this = ($this->input->post('this'))?$this->input->post('this'):0;
$this2 = ($this->input->post('this2'))?$this->input->post('this2'):0;
and then at the end you can make total of them and save them to database. OR as suggested above in comments that make your columns as DEFAULT 0 in your table.
------- IN YOUR CASE------
function insert()
{
$data['total']=0;
$data['user'] = $this->input->post('user');
$data['ghi'] = ($this->input->post('ghi'))?$this->input->post('ghi'):0;
$data['abc'] = ($this->input->post('abc'))?$this->input->post('abc'):0;
$data['def'] = ($this->input->post('def'))?$this->input->post('def'):0;
$data['total'] = $data['ghi'] + $data['abc'] + $data['def'];
$data['freight_charges'] = $this->input->post('freight_charges');
$this->db->insert('invoice',$data);
}
---------------IN JavaScript------------
on your event handler you can sum these by their IDs.
var total = parseInt($('#ghi').val())+parseInt($('#def').val());
and then show this total in your total div
$('#yourTotalDiv').text(total);
Displaying total amount on enter the details.
<script>
function showRequiredOption(cval)
{
if((cval=='interstate') || (cval == "stocktransfers"))
{
$('#ghi').hide();
$('#def').hide();
$('#abc').show();
}
else if ((cval=='exemptedsales') || (cval=="zeroratedsales") || (cval=="jobwork"))
{
$('#ghi').hide();
$('#def').hide();
$('#abc').hide();
}
else
{
$('#abc').hide();
$('#ghi').show();
$('#def').show();
}
}
</script>
<script>
$(document).ready(function(){
//iterate through each textboxes and add keyup
//handler to trigger sum event
$(".txt").each(function() {
$(this).keyup(function(){
calculateSum();
});
});
});
function calculateSum() {
var sum = 0;
//iterate through each textboxes and add the values
$(".txt").each(function() {
//add only if the value is number
if(!isNaN(this.value) && this.value.length!=0) {
sum += parseFloat(this.value);
}
});
//.toFixed() method will roundoff the final sum to 2 decimal places
$("#sum").html(sum.toFixed(2));
}
</script>
<div class="col-md-9 col-md-offset-2">
<div id="legend">
<legend class="">Profile Information</legend>
</div>
<form role="form" action="<?php echo site_url();?>invoice/addinvoice" method="post" class="form-horizontal" id="location" method="post" accept-charset="utf-8">
<div class="form-group">
<label class="control-label col-sm-2 " for="user">User</label>
<div class="col-sm-4 col-sm-offset-1">
<select id="user" name="user" onchange="showRequiredOption(this.value)">
<option value="employee">Local Sales</option>
<option value="interstate">Inter state</option>
<option value="stocktransfers">Stock transfers</option>
<option value="exemptedsales">Exempted Sales</option>
<option value="zeroratedcompany">Zero Rated Sales</option>
<option value="jobwork">Job Work</option>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2 " for="freight_charges">Freight Charges</label>
<div class="col-sm-4 col-sm-offset-1">
<input type="text" class="form-control txt" id="freight_charges" name="freight_charges" value="<?php echo set_value('freight_charges');?>" />
</div>
</div>
<div class="form-group" id="abc" style="display:none;">
<label class="control-label col-sm-2 " for="abc">ABC</label>
<div class="col-sm-4 col-sm-offset-1">
<input type="text" class="form-control txt" id="abc" name="abc" value="<?php echo set_value('abc');?>"/ >
</div>
</div>
<div class="form-group" id="def">
<label class="control-label col-sm-2 " for="def">DEF </label>
<div class="col-sm-4 col-sm-offset-1">
<input type="text" class="form-control txt" id="def" name="def" value="<?php echo set_value('def');?>"/ >
</div>
</div>
<div class="form-group" id="ghi">
<label class="control-label col-sm-2 " for="ghi">GHI</label>
<div class="col-sm-4 col-sm-offset-1">
<input type="text" class="form-control txt" id="ghi" name="ghi" value="<?php echo set_value('ghi');?>"/ >
</div>
</div>
<div class="form-group" id="summation">
<label class="control-label col-sm-2 " for="total">Total</label>
<div class="col-sm-4 col-sm-offset-1">
<span id="sum" class="form-control" type="text" name="total">0</span>
</div>
</div>
<button id="submit" type="submit" class="btn" name="submit">Submit</button>
</form>
</div>

Categories