the_mechanic/app/Views/job_card_form.php
2024-05-02 17:13:02 +05:30

1378 lines
70 KiB
PHP

<?php include('layout/header.php'); ?>
<div class="row">
<div class="col-12">
<div class="page-title-box page-title-box-alt">
<h4 class="page-title"><?php echo $page_name?></h4>
<div class="page-title-right">
<a href="<?= base_url() . "sales_order_index"; ?>" class="btn btn-secondary waves-effect">Cancel</a>
<ol class="breadcrumb m-0">
</li>
<!-- <li class="breadcrumb-item"><a href="javascript: void(0);">Tables</a></li>
<li class="breadcrumb-item active">Datatables</li> -->
</ol>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-body">
<form id="form-submit" action="<?= base_url() . "add_jobs"; ?>" method="post">
<input type="hidden" id="product_response" name="products" value="">
<input type="hidden" id="delete_items" name="delete_items" value="">
<!-- <h4 class="header-title">Sales Order Details :</h4><br> -->
<div class="form-row">
<div class="form-group col-md-3">
<label for="inputEmail4" class="col-form-label">Vehicle<span class="text-danger">*</span></label>
<?= isset($sales['vehicle_id']) ? '' : '<i type="button" class="fe-plus-circle" id="addVehicleModalButton" style="font-size: 18px;" data-toggle="modal" data-target="#addVehicleModal" title="Add Client"></i>' ?>
<select class="form-control vehicle-select SelExample" name="vehicle_id" <?= isset($sales['vehicle_id']) ? 'readonly' : 'required' ?>>
<?= isset($sales['vehicle_id']) ? '' : '<option value="">Select a vehicle</option>' ?>
<?php foreach ($vehicle as $value) : ?>
<?php if ((int)$value["isactive"] === 1) : ?>
<option value="<?= $value["vehicle_id"] ?>" <?= isset($jobs['vehicle_id']) && $jobs['vehicle_id'] == $value["vehicle_id"] ? 'selected' : '' ?>>
<?= $value["reg_no"]?>
</option>
<?php endif; ?>
<?php endforeach; ?>
</select>
</div>
<div class="form-group col-md-3">
<label for="inputPassword4" class="col-form-label">Make and Model</label>
<input type="text" class="form-control" id="makeAndModel" value="<?php echo isset($make_model) ? $make_model : ''; ?>" readonly>
</div>
<div class="form-group col-md-3">
<label for="inputPassword4" class="col-form-label">Client Name<span class="text-danger"></span></label>
<input type="text" class="form-control" name="client_id" placeholder="Client"value="<?= isset($jobs['client_name']) ? $jobs['client_name'] : '' ?>" readonly>
</div>
<div class="form-group col-md-3">
<label for="inputPassword4" class="col-form-label">Mobile No<span class="text-danger">*</span></label>
<input type="text" class="form-control" name="mobile_no" placeholder="Mobile" value="<?= isset($jobs['client_mobile_no']) ? $jobs['client_mobile_no'] : '' ?>" maxlength="10" minlength="10" onkeypress = "return onlyNumbers(event)" readonly>
</div>
</div><br>
<h4 class="header-title">Billing Address Details :</h4><br>
<div class="form-row">
<div class="form-group col-md-3">
<label for="inputPassword4" class="col-form-label">Address<span class="text-danger"></span></label>
<input type="text" class="form-control" name="billing_address" placeholder="Address"value="<?= isset($jobs['billing_address']) ? $jobs['billing_address'] : '' ?>" >
</div>
<input type="hidden" id="job_card_id" name="job_card_id" value="<?= isset($jobs['job_card_id']) ? $jobs['job_card_id'] : '' ?>"readonly>
<div class="form-group col-md-3">
<label for="inputPassword4" class="col-form-label">City<span class="text-danger"></span></label>
<input type="text" class="form-control" name="city" placeholder="City"value="<?= isset($jobs['billing_city']) ? $jobs['billing_city'] : 'Chennai' ?>" >
</div>
<div class="form-group col-md-3">
<label for="inputPassword4" class="col-form-label">State<span class="text-danger"></span></label>
<input type="text" class="form-control" name="state" placeholder="State"value="<?= isset($jobs['billing_state']) ? $jobs['billing_state'] : 'Tamil Nadu' ?>" >
</div>
<div class="form-group col-md-3">
<label for="inputPassword4" class="col-form-label">Pin Code<span class="text-danger"></span></label>
<input type="text" class="form-control" name="postalcode" placeholder="Pin Code"value="<?= isset($jobs['billing_postal_code']) ? $jobs['billing_postal_code'] : '' ?>" maxlength="6" minlength="6" >
</div>
</div>
<div class="form-row">
<div class="form-group col-md-3">
<label for="inputPassword4" class="col-form-label">Status<span class="text-danger">*</span>(<?php echo isset($jobs['status']) ? $jobs['status'] : '' ?>)</label>
<select class="form-control status-select" name="status" required data-toggle="select2">
<?php if (isset($jobs['status'])): ?>
<?php if ($jobs['status'] === 'Cancelled'): ?>
<option value="Created" <?= $jobs['status'] === 'Created' ? 'selected' : '' ?>>Created</option>
<option value="Paid" <?= $jobs['status'] === 'Paid' ? 'selected' : '' ?>>Paid</option>
<?php else: ?>
<option value="Paid" <?= $jobs['status'] === 'Paid' ? 'selected' : '' ?>>Paid</option>
<option value="Cancelled" <?= $jobs['status'] === 'Cancelled' ? 'selected' : '' ?>>Cancelled</option>
<?php endif; ?>
<?php else: ?>
<option value="Created" selected>Created</option>
<option value="Paid">Paid</option>
<?php endif; ?>
</select>
</div>
<?php if(isset($workers) && $jobs['status'] == 'Paid') { ?>
<div class="form-group col-md-3">
<label for="inputPassword4" class="col-form-label">Assign To</label>
<select class="form-control SelExample" name="assigned_to[]" id="assigned_to" required multiple>
<?= isset($jobs['assigned_to']) ? '' : '<option value="">Select a Make</option>' ?>
<?php foreach ($workers as $value) : ?>
<?php if ((int)$value["isactive"] === 1) : ?>
<option value="<?= $value["user_id"] ?>" <?= isset($jobs['assigned_to']) && in_array($value["user_id"], json_decode($jobs['assigned_to'])) ? 'selected' : '' ?>>
<?= $value["name"]; ?>
</option>
<?php endif; ?>
<?php endforeach; ?>
</select>
</div>
<?php } ?>
<?php if(session()->get('logged_user_role') == 'Store Manager') { ?>
<div class="form-group col-md-3">
<label for="inputPassword4" class="col-form-label">Item Issued</label>
<select class="form-control SelExample" name="store_item_issued" id="store_item_issued" required>
<option value="0" <?= isset($jobs['store_item_issued']) && ($jobs["store_item_issued"] == 0) ? 'selected' : '' ?> >Not Issued Item</option>
<option value="1" <?= isset($jobs['store_item_issued']) && ($jobs["store_item_issued"] == 1) ? 'selected' : '' ?> >Item Issued</option>
</select>
</div>
<?php } ?>
</div>
<div class="form-row" id="itemTableContainer">
<div class="form-group col-md-12">
<h4>Item Details</h4>
<br />
<table class="table table-bordered" id="productItemTable">
<thead>
<tr>
<th hidden></th>
<th>Item Details</th>
<th>Qty</th>
<th>Rate</th>
<th>Tax</th>
<th>Amount</th>
<th style="width: 10px;">Action</th>
<th hidden></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<div class="form-group text-right m-b-0">
<!-- Show the "Add More Item" button only if invoice_type is not 1 -->
<a class="btn" id="addService">
<h4><i class="fa fa-plus" aria-hidden="true"></i> Add Service</h4>
</a>
<a class="btn" id="addcomplaint">
<h4><i class="fa fa-plus" aria-hidden="true"></i> Add Complaint</h4>
</a>
<a class="btn" id="addCustomComplaint">
<h4><i class="fa fa-plus" aria-hidden="true"></i> Add Custom Complaint</h4>
</a>
</div>
</div>
</div>
<div class="form-row">
<div class="offset-md-7 col-md-5 card">
<div class="card-body">
<h4>Calculation</h4>
<div class="form-group">
<label for="subtotal">Subtotal</label>
<input type="text" class="form-control" id="subtotal" name="sub_total" value="<?= isset($sales['subtotal']) ? $sales['subtotal'] : '' ?>"readonly >
</div>
<div class="form-group">
<label for="invoicetax">Tax Amount<span id=""></span></label>
<input type="text" class="form-control" id="invoicetax" name="invoicetax" readonly value="<?= isset($sales['tax']) ? $sales['tax'] : '' ?>">
</div>
<div class="form-group">
<label for="grandtotal">Total</label>
<input type="text" class="form-control" id="grandtotal" name="grand_total" readonly value="<?= isset($sales['total']) ? $sales['total'] : '' ?>">
</div>
</div>
</div>
</div>
<h4 class="header-title">Terms & Condition :</h4><br>
<div class="form-row">
<div class="form-group col-md-12">
<label for="inputPassword4" class="col-form-label">Terms & Condition</label>
<textarea class="form-control" name="terms_condition" placeholder="Terms & Condition" >
<?= isset($sales['terms_condition']) ? $sales['terms_condition'] : 'Please check the products properly before purchase. Products once sold cannot be returned.' ?>
</textarea>
</div>
</div>
<?php if (!isset($sales['status']) || $sales['status'] !== 'Paid') : ?>
<button type="submit" id="submit-btn" class="btn btn-primary">Submit</button>
<?php endif; ?>
</form>
</div>
</div>
</div>
</div>
<?php include('layout/footer.php'); ?>
</div>
<div class="modal fade" id="addVehicleModal" tabindex="-1" role="dialog" aria-labelledby="addVehicleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="addVehicleModalLabel">Add New Vehicle</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body">
<form >
<div class="form-row">
<div class="form-group col-md-6">
<!-- <div class="form-group"> -->
<label for="inputPassword4" class="col-form-label">Make</label>
<select class="form-control SelExample" name="make" id="make" <?= isset($vehicle['make']) ? '' : 'required' ?>>
<?= isset($vehicle['make']) ? '' : '<option value="">Select a Make</option>' ?>
<?php foreach ($makeData as $value) : ?>
<?php if ((int)$value["isactive"] === 1) : ?>
<option value="<?= $value["make_id"] ?>" <?= isset($vehicle['make']) && $vehicle['make'] == $value["make_id"] ? 'selected' : '' ?>>
<?= $value["make"]; ?>
</option>
<?php endif; ?>
<?php endforeach; ?>
</select>
</div>
<div class="form-group col-md-6">
<label for="inputPassword4" class="col-form-label">Model</label>
<select class="form-control SelExample" name="model" id="model" <?= isset($vehicle['model']) ? '' : 'required' ?>>
<?php if (isset($vehicle["model_name"])) : ?>
<option value="<?= $vehicle["model"] ?>" >
<?= $vehicle["model_name"]; ?>
</option>
<?php endif; ?>
</select>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-12">
<label for="inputPassword4" class="col-form-label">Reg Number</label>
<input type="text" class="form-control" name="reg_no" id="reg_no" placeholder="Reg Number"value="<?= isset($vehicle['reg_no']) ? $vehicle['reg_no'] : '' ?>" required>
</div>
</div>
<div class="form-row">
<input type="text" value="select" id="formType" hidden>
<div class="form-group col-md-12 select">
<label for="clientName">Client Name</label>
<i type="button" class="fe-user-plus" id="createClient" style="font-size: 18px;" ></i>
<select class="form-control cleint-select SelExample" id="clientName" required>
<option value="">Select a Client</option>
<?php foreach ($client as $value) : ?>
<option value="<?= $value["client_id"] ?>">
<?= $value["mobile_no"] .' - '. $value["client_name"]; ?>
</option>
<?php endforeach; ?>
</select>
</div>
<div class="form-group col-md-12 select">
<label for="clientMobile">Mobile</label>
<input type="text" class="form-control" id="clientMobile" placeholder="Enter mobile number" maxlength="10" minlength="10"onkeypress = "return onlyNumbers(event)"required>
</div>
<div class="form-group col-md-12 create" style="display:none;">
<label for="create-clientName">Client Name</label>
<i type="button" class="fe-user-check" id="selectClient" style="font-size: 18px;" ></i>
<input type="text" class="form-control" id="create-clientName" placeholder="Enter client name" required>
</div>
<div class="form-group col-md-6 create" style="display:none;">
<label for="create-clientMobile">Mobile</label>
<input type="text" class="form-control" id="create-clientMobile" placeholder="Enter mobile number" maxlength="10" minlength="10"onkeypress = "return onlyNumbers(event)"required>
</div>
<div class="form-group col-md-6 create" style="display:none;">
<label for="create-clientType">Client Type</label>
<select class="form-control status-select" id="create-clientType" required >
<option value="">Select a Type</option>
<option value="Direct" >Direct</option>
<option value="Mechanic" >Mechanic</option>
<option value="Exp" >Exp</option>
</select>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" id="saveVehcileBtn">Save Vehicle</button>
</div>
</div>
</div>
</div>
<script>
/***** APPEND DATA ONLY EDIT ******/
$(document).ready(async function() {
/** SERVICE */
var edit_service_data = <?php echo isset($editservicedata) ? json_encode($editservicedata) : 0 ?>;
if(edit_service_data.length > 0) {
for (const value of edit_service_data) {
servicearray = <?php echo isset($service_1) ? json_encode($service_1) : json_encode($service) ?>;
// console.log(servicearray);
var newRow = `<tr class="service_class"><td hidden style="width:10%;">
<input type="number" class="form-control labour_cost" name="labour_cost" value="${value.labour_cost}"></td>
<td><select class="form-control book-select SelExample service" name="service_details[]" required data-toggle="select2" style="width: 249px !important;">
<option value="">Select a Service</option>`;
for (var i = 0; i < servicearray.length; i++)
{
var service = servicearray[i];
newRow += '<option value="' + service.service_id + '" ' + (value.service_id == service.service_id ? "selected" : "") + '>' + service.service_name + '</option>';
}
newRow += '</select></td>' +
'<td style="width:10%;"><input type="number" class="form-control item-quantity" min="0" value="'+value.qty+'" name="quantity[]" readonly/></td>' +
'<td style="width:10%;"><input type="text" class="form-control item-rate" value="'+value.amount+'" name="unit-price[]" readonly /></td>' +
'<td style="width:8%;"><input type="text" class="form-control item-tax" value="'+value.tax+'" name="item-tax[]" readonly /></td>' +
'<td style="width:12%;"><input type="text" class="form-control item-amount" value="'+value.amount+'" name="amount[]"/></td>' +
'<td><center><i class="fa fa-trash remove-item"></i></center><input value="service" name="item_type" hidden></td>' +
'<td hidden><input name="id" value="'+value.job_card_service_id+'"></td>' +
'</tr>';
// console.log(value);
tr = $('#productItemTable tbody').append(newRow);
initializeSelect2();
/** APPEND CHILD PRODUCT */
await edit_product_data(value.product);
editlabourcost(value.labour_cost);
}
}
/** COMPLAINT */
var edit_complaint_data = <?php echo isset($editcomplaintdata) ? json_encode($editcomplaintdata) : 0 ?>;
if(edit_complaint_data.length > 0) {
for (const value of edit_complaint_data) {
complaint = <?php echo json_encode($complaint) ?>;
// console.log(productarray);
var newRow = '<tr class="complaint_class"><td hidden style="width:10%;"> <input type="number" class="form-control labour_cost" name="labour_cost" value="'+value.labour_cost+'"></td><td><select class="form-control book-select SelExample complaint" id="complaint_detail" name="complaint_details[]" required data-toggle="select2" style="width: 249px !important;"><option value="">Select a Complaint</option>';
for (var i = 0; i < complaint.length; i++)
{
var complaints = complaint[i];
newRow += '<option value="' + complaints.complaint_id + '" ' + (value.complaint_id == complaints.complaint_id ? "selected" : "") + '>' + complaints.name + '</option>';
}
newRow += '</select></td>' +
'<td style="width:10%;"><input type="number" class="form-control item-quantity" min="0" value="'+value.qty+'" name="quantity[]" readonly/></td>' +
'<td style="width:10%;"><input type="text" class="form-control item-rate" value="'+value.amount+'" name="unit-price[]" readonly /></td>' +
'<td style="width:8%;"><input type="text" class="form-control item-tax" value="'+value.tax+'" name="item-tax[]" readonly /></td>' +
'<td style="width:12%;"><input type="text" class="form-control item-amount" value="'+value.amount+'" name="amount[]"/></td>' +
'<td><div style="display: inline-block;">'+
'<center><i class="fa fa-trash remove-item"></i></center>'+
'</div>'+
'<div style="display: inline-block; margin-left: 10px;">'+
'<input value="product" name="item_type" hidden>'+
'<a class="complaint_detail" id="addProduct" title="Add Product">'+
'<i class="fa fa-plus" aria-hidden="true"></i>'+
'</a>'+
'</div>'+
'</td>' +
'<td hidden><input type="hidden" name="id" value="'+value.job_card_complaint_id+'"></td>' +
'</tr>';
$('#productItemTable tbody').append(newRow);
initializeSelect2();
/** APPEND CHILD PRODUCT */
await edit_product_data(value.product);
editlabourcost(value.labour_cost)
}
}
/** CUSTOM COMPLAINT */
var edit_ccomplaint_data = <?php echo isset($editccomplaintdata) ? json_encode($editccomplaintdata) : 0 ?>;
if(edit_ccomplaint_data.length > 0) {
for (const value of edit_ccomplaint_data) {
var newRow = '<tr class="custom_complaint_class"><td hidden style="width:10%;"> <input type="number" class="form-control labour_cost" name="labour_cost" value="'+value.labour_cost+'"></td><td><textarea class="form-control custom-comp" id="custom_complaint_detail" rows="5">'+value.name+'</textarea></td>' +
'<td style="width:10%;"><input type="number" class="form-control item-quantity" min="0" value="'+value.qty+'" name="quantity[]" readonly/></td>' +
'<td style="width:10%;"><input type="text" class="form-control item-rate" value="'+value.amount+'" name="unit-price[]" /></td>' +
'<td style="width:8%;"><input type="text" class="form-control item-tax" value="'+value.tax+'" name="item-tax[]" /></td>' +
'<td style="width:12%;"><input type="text" class="form-control item-amount" value="'+value.amount+'" name="amount[]"/></td>' +
'<td><div style="display: inline-block;">'+
'<center><i class="fa fa-trash remove-item"></i></center>'+
'</div>'+
'<div style="display: inline-block; margin-left: 10px;">'+
'<input value="product" name="item_type" hidden>'+
'<a class="custom_complaint_detail" id="addProduct" title="Add Product">'+
'<i class="fa fa-plus" aria-hidden="true"></i>'+
'</a>'+
'</div>'+
'</td>' +
'<td hidden><input type="hidden" name="id" value="'+value.job_card_cc_id+'"></td>' +
'</tr>';
$('#productItemTable tbody').append(newRow);
initializeSelect2();
/** APPEND CHILD PRODUCT */
await edit_product_data(value.product);
editlabourcost(value.labour_cost)
}
}
function editlabourcost(data) {
var newRow = '<tr class="dummy"><td hidden style="width:10%;"><input type="number" class="form-control labour_cost" name="labour_cost"></td><td style="padding-left: 40px !important;"><i class="fa fa-caret-right" style="font-size: 20px;margin-top: 8px;position: absolute;margin-left: -18px;" aria-hidden="true"></i><input type="text" class="form-control labour_cost" value="Labour Cost"></td>' +
'<td style="width:10%;"></td>' +
'<td style="width:10%;"></td>' +
'<td style="width:8%;"></td>' +
'<td style="width:12%;"><input type="text" class="form-control item-amount" name="amount[]" value="' + data + '" readonly/></td>' +
'<td hidden></td>' +
'<td hidden></td>' +
'</tr>';
$('#productItemTable tbody').append(newRow);
// $(newRow).insertAfter(tr);
initializeSelect2();
}
function edit_product_data(products) {
for (const product of products) {
var newRow = `<tr><td hidden style="width:10%;"><input type="number" class="form-control labour_cost" name="labour_cost"></td>
<td style="padding-left: 40px !important;"><i class="fa fa-caret-right" style="font-size: 20px;margin-top: 8px;position: absolute;margin-left: -18px;" aria-hidden="true"></i>
<select class="form-control book-select SelExample product" name="item_details[]" required data-toggle="select2" style="width: 249px !important;">`;
newRow += '<option value="' + product.product_id + '" selected>' + product.pname + '</option>';
newRow += '</select></td>' +
'<td style="width:10%;"><input type="number" class="form-control item-quantity" min="0" value="' + product.qty + '" name="quantity[]"/></td>' +
'<td style="width:10%;"><input type="text" class="form-control item-rate" name="unit-price[]" value="' + product.amount + '" readonly /></td>' +
'<td style="width:8%;"> <input type="text" class="form-control item-tax" name="item-tax[]" value="' + product.tax + '" readonly /></td>' +
'<td style="width:12%;"><input type="text" class="form-control item-amount" name="amount[]" value="' + product.amount + '" readonly/></td>' +
'<td hidden><input type="hidden"></td>' +
'<td hidden><input type="hidden" name="id" value="'+product.job_card_product_id+'"></td>' +
'</tr>';
$('#productItemTable tbody').append(newRow);
// $(newRow).insertAfter(tr);
initializeSelect2();
}
}
});
productarray = [];
servicearray = [];
$(document).ready(function() {
// Event listener for vehicle selection change
$('.vehicle-select').change(function() {
var vehicleId = $(this).val();
fetch_data(vehicleId)
});
if($('.vehicle-select').val()) {
fetch_data($('.vehicle-select').val())
}
function fetch_data(vehicleId) {
if (vehicleId !== '') {
// Find the selected vehicle
var selectedVehicle = vehicles.find(function(vehicle) {
return vehicle.vehicle_id == vehicleId;
});
// Extract makeId from the selected vehicle
var makeId = selectedVehicle.make;
var modelId = selectedVehicle.model;
// console.log(modelId);
// Make sure makeId exists
if (makeId !== undefined) {
// Perform AJAX request to fetch product information
$.ajax({
url: '<?php echo base_url().'getProducts'?>', // Replace with the actual backend endpoint
method: 'POST', // or 'GET' based on your server implementation
dataType: 'json',
data: {
make_id: makeId,
model_id:modelId,
vehicle_id: vehicleId
},
success: function(response) {
console.log(response);
productarray = response.product;
makeAndModel = response.makeName+' '+response.modelName;
$('#makeAndModel').val(makeAndModel);
},
error: function(xhr, status, error) {
// Handle error
console.error('Error fetching product information:', error);
}
});
$.ajax({
url: '<?php echo base_url().'getServices'?>', // Replace with the actual backend endpoint
method: 'POST', // or 'GET' based on your server implementation
dataType: 'json',
data: {
make_id: makeId,
model_id:modelId,
vehicle_id: vehicleId
},
success: function(response) {
console.log(response);
servicearray = response.service;
makeAndModel = response.makeName+' '+response.modelName;
// $('#makeAndModel').val(makeAndModel);
},
error: function(xhr, status, error) {
// Handle error
console.error('Error fetching product information:', error);
}
});
} else {
console.error('Make ID not found for the selected vehicle');
}
}
}
});
<?php
$product_json = isset($product_1) ? json_encode($product_1) : json_encode($product);
$service_json = isset($service_1) ? json_encode($service_1) : json_encode($service);
?>
$(document).ready(function() {
function validateProductAdded() {
var rowCount = $('#itemTable tbody tr').length;
return true;
}
// Event listener for form submission
$('form').submit(function() {
return validateProductAdded();
});
$(document).on('keyup change', '.item-amount', function() {
// Calculate amount and update amount input field
updateCalculations();
});
var products = <?php echo $product_json; ?>;
var services = <?php echo $service_json; ?>;
var complaint = <?php echo json_encode($complaint) ?>;
var mapTable;
function data_contruction_for_save() {
var dataMapArray = [{ 'service': [], 'complaint': [], 'custom_complaint': [] }];
// Select all <tr> elements within the tbody of the table with id productItemTable
var tableRows = document.querySelectorAll("#productItemTable tbody tr");
// Loop through each <tr> element
tableRows.forEach(function(row) {
var firstTd = row.querySelector("td:nth-child(1)");
var secondTd = row.querySelector("td:nth-child(2)");
var thirdTd = row.querySelector("td:nth-child(3)");
var fifthTd = row.querySelector("td:nth-child(5)");
var sixthTd = row.querySelector("td:nth-child(6)");
var eigthTd = row.querySelector("td:nth-child(8)");
// Check if the second <td> element contains a <select> element
var selectFirstElement = firstTd.querySelector("input");
var selectElement = secondTd.querySelector("select, textarea");
var selectThirdElement = thirdTd.querySelector("input");
var selectFifthElement = fifthTd.querySelector("input");
var selectsixthElement = sixthTd.querySelector("input");
var selecteightElement = eigthTd.querySelector("input");
if (selectElement) {
// Get the class name of the <select> element
var className = selectElement.className;
// Get the selected value of the <select> element
var selectedValue = selectElement.value;
var quality = selectThirdElement.value;
var tax = selectFifthElement.value;
var amount = selectsixthElement.value;
var id = selecteightElement.value;
var labour_cost = selectFirstElement.value;
// Output the class name and selected value
// console.log("Class Name: " + className + ", Selected Value: " + selectedValue);
if (className.includes("product"))
{
if(mapTable == "service") {
addProductToLastObjectByKey(dataMapArray, "service", [{ 'id': id, 'p_id' : selectedValue , 'qty' : quality, 'tax': tax, 'amount': amount }]);
}
else if(mapTable == "complaint") {
addProductToLastObjectByKey(dataMapArray, "complaint", [{ 'id': id, 'p_id' : selectedValue , 'qty' : quality, 'tax': tax, 'amount': amount }]);
}
else if(mapTable == "custom-comp") {
addProductToLastObjectByKey(dataMapArray, "custom_complaint", [{ 'id': id, 'p_id' : selectedValue , 'qty' : quality, 'tax': tax, 'amount': amount }]);
}
}
else if(className.includes("service"))
{
mapTable = "service";
dataMapArray[0].service.push({'id': id, 'labour_cost': labour_cost, 'service_id' : selectedValue , 'quality' : quality, 'tax': tax, 'amount': amount });
}
else if(className.includes("complaint"))
{
mapTable = "complaint";
dataMapArray[0].complaint.push({ 'id': id, 'labour_cost': labour_cost, 'complaint_id' : selectedValue , 'quality' : quality, 'tax': tax, 'amount': amount });
}
else if(className.includes("custom-comp"))
{
mapTable = "custom-comp";
dataMapArray[0].custom_complaint.push({ 'id': id, 'labour_cost': labour_cost, 'complaint_id' : selectedValue , 'quality' : quality, 'tax': tax, 'amount': amount });
}
}
});
console.log(dataMapArray,'dataMapArray');
$('#product_response').val(JSON.stringify(dataMapArray))
}
function addProductToLastObjectByKey(array, key, product) {
console.log(product);
for (const obj of array) {
if (obj[key]) {
const lastObjectIndex = obj[key].length - 1;
const lastObject = obj[key][lastObjectIndex];
if (!lastObject.product) {
lastObject.product = product;
}
else {
lastObject.product.push(product[0]);
}
}
}
console.log(array,'dataMapArray11');
}
$(document).ready(function() {
$('#submit-btn').click(function(event) {
// Prevent the default form submission
event.preventDefault();
data_contruction_for_save();
$("#delete_items").val(JSON.stringify(delete_items_id));
$('#form-submit').submit();
});
});
// Event listener for product selection
$(document).on('change', 'select[name="item_details[]"]', function() {
// Get class name of the select element
var className = $(this).attr('class');
var productId = $(this).val();
var quantity = $(this).closest('tr').find('.item-quantity').val(1);
if (className.includes("product")) {
// Find product details from JSON
var product = products.find(function(item) {
return item.product_id == productId;
});
// Access unit price from product and set it as rate
var unitPrice = parseFloat(product.unit_price); // Convert to float if necessary
$(this).closest('tr').find('.item-rate').val(unitPrice);
// Calculate amount and update amount input field
// calculateAmount($(this).closest('tr'));
}
calculateAmount($(this).closest('tr'),className);
updateCalculations();
});
// Event listener for product selection
$(document).on('change', 'select[name="service_details[]"]', async function() {
/*** REMOVE SUBPRODUCT ONCHANGE */
var $closestTR = $(this).closest('tr');
while ($closestTR.next().length > 0 && $closestTR.attr('class') != "product") {
if ($closestTR.next().hasClass('service_class') || $closestTR.next().hasClass('complaint_class') || $closestTR.next().hasClass('custom_complaint_class')) {
break;
}
// Remove the next row
$closestTR.next().remove();
}
// Get class name of the select element
var className = $(this).attr('class');
var productId = $(this).val();
var quantity = $(this).closest('tr').find('.item-quantity').val(1);
if(className.includes("service")) {
// Find product details from JSON
var service_data = services.find(function(item) {
return item.service_id == productId;
});
// Access unit price from product and set it as rate
var unitPrice = parseInt(service_data.price); // Convert to float if necessary
console.log(service_data);
$(this).closest('tr').find('.item-rate').val(unitPrice);
$(this).closest('tr').find('.labour_cost').val(parseInt(service_data.labour_cost));
await labourcost(service_data.labour_cost,$(this).closest('tr'));
service_child_products(service_data,$(this).closest('tr'))
}
calculateAmount($(this).closest('tr'),className);
updateCalculations();
});
// Event listener for product selection
$(document).on('change', 'select[name="complaint_details[]"]', async function() {
// Get class name of the select element
var className = $(this).attr('class');
var productId = $(this).val();
var quantity = $(this).closest('tr').find('.item-quantity').val(1);
if(className.includes("complaint")) {
// Find product details from JSON
var complaint_data = complaint.find(function(item) {
return item.complaint_id == productId;
});
// Access unit price from product and set it as rate
var unitPrice = parseInt(complaint_data.labour_charge); // Convert to float if necessary
$(this).closest('tr').find('.item-rate').val(unitPrice);
$(this).closest('tr').find('.labour_cost').val(parseInt(complaint_data.labour_charge));
await labourcost(complaint_data.labour_charge,$(this).closest('tr'));
}
calculateAmount($(this).closest('tr'),className);
updateCalculations();
});
// Function to calculate amount based on rate and quantity
function calculateAmount(row,type) {
// console.log(row);
var rate = $(row).find('.item-rate').val();
var quantity = $(row).find('.item-quantity').val();
var amount = rate * quantity;
$(row).find('.item-amount').val(amount);
// Retrieve CGST and SGST values from the database for the selected product
var productId = $(row).find('select[name="item_details[]"]').val();
if (type.includes("product")) {
var product = products.find(function(item) {
return item.product_id == productId;
});
console.log(product);
var cgst = parseFloat(product.cgst);
var sgst = parseFloat(product.sgst);
// Calculate total tax by adding CGST and SGST
var tax = cgst + sgst;
$(row).find('.item-tax').val(tax.toFixed(2));
}
else if(type.includes("service")) {
var productId = $(row).find('select[name="service_details[]"]').val();
var product = services.find(function(item) {
return item.service_id == productId;
});
var cgst = parseFloat(product.cgst);
var igst = parseFloat(product.sgst);
// Calculate total tax by adding CGST and SGST
var tax = cgst + igst;
console.log(tax);
$(row).find('.item-tax').val(tax.toFixed(2));
}
else if(type.includes("complaint")) {
var productId = $(row).find('select[name="complaint_details[]"]').val();
var product = complaint.find(function(item) {
return item.complaint_id == productId;
});
console.log(product);
var cgst = parseFloat(product.cgst);
var igst = parseFloat(product.sgst);
// Calculate total tax by adding CGST and SGST
var tax = cgst + igst;
$(row).find('.item-tax').val(tax.toFixed(2));
}
}
const labourcost = async (data,tr) => {
var newRow = '<tr class="dummy"><td hidden style="width:10%;"><input type="number" class="form-control labour_cost" name="labour_cost"></td><td style="padding-left: 40px !important;"><i class="fa fa-caret-right" style="font-size: 20px;margin-top: 8px;position: absolute;margin-left: -18px;" aria-hidden="true"></i><input type="text" class="form-control labour_cost" value="Labour Cost"></td>' +
'<td style="width:10%;"></td>' +
'<td style="width:10%;"></td>' +
'<td style="width:8%;"></td>' +
'<td style="width:12%;"><input type="text" class="form-control item-amount" name="amount[]" value="' + data + '" readonly/></td>' +
'<td hidden></td>' +
'<td hidden></td>' +
'</tr>';
// $('#productItemTable tbody').append(newRow);
$(newRow).insertAfter(tr);
initializeSelect2();
}
const service_child_products = async (data,tr) => {
console.log(JSON.parse(data.product_id));
JSON.parse(data.product_id).forEach(async(element,index) => {
if(element == 0) return;
var product = products.find(function(item) {
return item.product_id == element;
});
var cgst = parseFloat(product.cgst);
var sgst = parseFloat(product.sgst);
// Calculate total tax by adding CGST and SGST
var tax = cgst + sgst;
var newRow = '<tr class="product"><td hidden style="width:10%;"><input type="number" class="form-control labour_cost" name="labour_cost"></td><td style="padding-left: 40px !important;"><i class="fa fa-caret-right" style="font-size: 20px;margin-top: 8px;position: absolute;margin-left: -18px;" aria-hidden="true"></i><select class="form-control book-select SelExample product" name="item_details[]" required data-toggle="select2" style="width: 249px !important;">';
newRow += '<option value="' + product.product_id + '">' + product.product_name + '</option>';
newRow += '</select></td>' +
'<td style="width:10%;"><input type="number" class="form-control item-quantity" min="0" value="1" name="quantity[]" readonly/></td>' +
'<td style="width:10%;"><input type="text" class="form-control item-rate" name="unit-price[]" value="' + product.unit_price + '" readonly /></td>' +
'<td style="width:8%;"> <input type="text" class="form-control item-tax" name="item-tax[]" value="' + tax + '" readonly /></td>' +
'<td style="width:12%;"><input type="text" class="form-control item-amount1" name="amount1[]" value="' + product.unit_price + '" readonly/></td>' +
'<td hidden><input type="hidden"></td>' +
'<td hidden><input type="hidden" name="id" value=""></td>' +
'</tr>';
// $('#productItemTable tbody').append(newRow);
$(newRow).insertAfter(tr);
initializeSelect2();
});
}
// Event listener for quantity change
$(document).on('input change', '.item-quantity', async function() {
calculateAmount($(this).closest('tr'));
updateCalculations();
});
$(document).on('click', '.item-quantity', async function() {
updateCalculations();
});
// Function to calculate subtotal
function calculateSubtotal() {
var subtotal = 0;
$('.item-amount').each(function() {
subtotal += parseFloat($(this).val()) || 0;
});
return subtotal;
}
// Function to calculate total tax
function calculateTax() {
var tax = 0;
$('.item-tax').each(function() {
var taxPercentage = parseFloat($(this).val()) || 0;
var amount = parseFloat($(this).closest('tr').find('.item-amount').val()) || 0;
var taxValue = (taxPercentage / 100) * amount; // Convert percentage to absolute value
tax += taxValue;
});
return tax;
}
// Function to calculate total discount
function calculateDiscount() {
var totalDiscount = 0;
$('.item-discount-amount').each(function(index, element) {
var discountAmount = parseFloat($(element).val()) || 0;
var discountType = $(element).closest('tr').find('.item-discount-type').val();
if (discountType === '%') {
var rate = $(element).closest('tr').find('.item-rate').val();
var quantity = $(element).closest('tr').find('.item-quantity').val();
var amount = rate * quantity;
discountAmount = amount * discountAmount / 100;
}
totalDiscount += discountAmount;
});
return totalDiscount;
}
// Function to calculate total
function calculateTotal() {
var subtotal = calculateSubtotal();
var tax = calculateTax();
var discount = calculateDiscount();
var total = subtotal + tax - discount;
// return total;
return Math.round(total);
}
// Update subtotal, tax, and total
function updateCalculations() {
$('#subtotal').val(calculateSubtotal().toFixed(2));
$('#invoicetax').val(calculateTax().toFixed(2));
$('#discount').val(calculateDiscount().toFixed(2));
$('#grandtotal').val(calculateTotal().toFixed(2));
}
// Event listener for discount change
$(document).on('input', '.item-discount-amount, .item-discount-type', function() {
updateCalculations();
});
// Calculate initial values on page load
updateCalculations();
// Event listener for "Add More Item" button
$(document).on('click', '#addProduct', function() {
console.log(productarray.length);
if(productarray.length == 0) {
productarray = <?php echo json_encode($product) ?>;
console.log(productarray);
}
var newRow = '<tr class="product"><td hidden style="width:10%;"><input type="number" class="form-control labour_cost" name="labour_cost"></td><td style="padding-left: 40px !important;"><i class="fa fa-caret-right" style="font-size: 20px;margin-top: 8px;position: absolute;margin-left: -18px;" aria-hidden="true"></i><select class="form-control book-select SelExample product" name="item_details[]" required data-toggle="select2" style="width: 249px !important;"><option value="">Select a Product</option>';
for (var i = 0; i < productarray.length; i++)
{
var product = productarray[i];
newRow += '<option value="' + product.product_id + '">' + product.product_name + '</option>';
}
newRow += '</select></td>' +
'<td style="width:10%;"><input type="number" class="form-control item-quantity" min="0" name="quantity[]"/></td>' +
'<td style="width:10%;"><input type="text" class="form-control item-rate" name="unit-price[]" readonly /></td>' +
'<td style="width:8%;"><input type="text" class="form-control item-tax" name="item-tax[]" readonly /></td>' +
'<td style="width:12%;"><input type="text" class="form-control item-amount" name="amount[]"/></td>' +
'<td><center><i class="fa fa-trash remove-item"></i></center><input value="product" name="item_type" hidden></td>' +
'<td hidden><input type="hidden" name="id"></td>' +
'</tr>';
// $('#productItemTable tbody').append(newRow);
$(newRow).insertAfter($(this).closest('tr'));
initializeSelect2();
});
$('#addService').click(function() {
servicearray = <?php echo isset($service_1) ? json_encode($service_1) : json_encode($service) ?>;
// console.log(servicearray);
var newRow = '<tr class="service_class"><td hidden style="width:10%;"> <input type="number" class="form-control labour_cost" name="labour_cost"></td><td><select class="form-control book-select SelExample service" name="service_details[]" required data-toggle="select2" style="width: 249px !important;"><option value="">Select a Service</option>';
for (var i = 0; i < servicearray.length; i++)
{
var service = servicearray[i];
newRow += '<option value="' + service.service_id + '">' + service.service_name + '</option>';
}
newRow += '</select></td>' +
'<td style="width:10%;"><input type="number" class="form-control item-quantity" min="0" name="quantity[]" readonly/></td>' +
'<td style="width:10%;"><input type="text" class="form-control item-rate" name="unit-price[]" readonly /></td>' +
'<td style="width:8%;"><input type="text" class="form-control item-tax" name="item-tax[]" readonly /></td>' +
'<td style="width:12%;"><input type="text" class="form-control item-amount" name="amount[]"/></td>' +
'<td><center><i class="fa fa-trash remove-item" id="remove-item"></i></center><input value="service" name="item_type" hidden></td>' +
'<td hidden><input type="hidden" name="id"></td>' +
'</tr>';
$('#productItemTable tbody').append(newRow);
initializeSelect2();
});
$('#addcomplaint').click(function() {
complaint = <?php echo json_encode($complaint) ?>;
// console.log(productarray);
var newRow = '<tr class="complaint_class"><td hidden style="width:10%;"> <input type="number" class="form-control labour_cost" name="labour_cost"></td><td><select class="form-control book-select SelExample complaint" id="complaint_detail" name="complaint_details[]" required data-toggle="select2" style="width: 249px !important;"><option value="">Select a Complaint</option>';
for (var i = 0; i < complaint.length; i++)
{
var complaints = complaint[i];
newRow += '<option value="' + complaints.complaint_id + '">' + complaints.name + '</option>';
}
newRow += '</select></td>' +
'<td style="width:10%;"><input type="number" class="form-control item-quantity" min="0" name="quantity[]" readonly/></td>' +
'<td style="width:10%;"><input type="text" class="form-control item-rate" name="unit-price[]" readonly /></td>' +
'<td style="width:8%;"><input type="text" class="form-control item-tax" name="item-tax[]" readonly /></td>' +
'<td style="width:12%;"><input type="text" class="form-control item-amount" name="amount[]"/></td>' +
'<td><div style="display: inline-block;">'+
'<center><i class="fa fa-trash remove-item"></i></center>'+
'</div>'+
'<div style="display: inline-block; margin-left: 10px;">'+
'<input value="product" name="item_type" hidden>'+
'<a class="complaint_detail" id="addProduct" title="Add Product">'+
'<i class="fa fa-plus" aria-hidden="true"></i>'+
'</a>'+
'</div>'+
'</td>' +
'<td hidden><input type="hidden" name="id"></td>' +
'</tr>';
$('#productItemTable tbody').append(newRow);
initializeSelect2();
});
$('#addCustomComplaint').click(function() {
complaint = <?php echo json_encode($complaint) ?>;
// console.log(productarray);
var newRow = '<tr class="custom_complaint_class"><td hidden style="width:10%;"> <input type="number" class="form-control labour_cost" name="labour_cost"></td><td><textarea class="form-control custom-comp" id="custom_complaint_detail" rows="5"></textarea></td>' +
'<td style="width:10%;"><input type="number" class="form-control item-quantity" min="0" value="1" name="quantity[]" readonly/></td>' +
'<td style="width:10%;"><input type="text" class="form-control item-rate" name="unit-price[]" /></td>' +
'<td style="width:8%;"><input type="text" class="form-control item-tax" name="item-tax[]" /></td>' +
'<td style="width:12%;"><input type="text" class="form-control item-amount" name="amount[]"/></td>' +
'<td hidden><input type="hidden"></td>' +
'<td><div style="display: inline-block;">'+
'<center><i class="fa fa-trash remove-item"></i></center>'+
'</div>'+
'<div style="display: inline-block; margin-left: 10px;">'+
'<input value="product" name="item_type" hidden>'+
'<a class="custom_complaint_detail" id="addProduct" title="Add Product">'+
'<i class="fa fa-plus" aria-hidden="true"></i>'+
'</a>'+
'</div>'+
'</td>' +
'<td hidden><input type="hidden" name="id" value=""></td>' +
'</tr>';
newRow += '<tr class="dummy"><td hidden style="width:10%;"><input type="number" class="form-control labour_cost" name="labour_cost"></td><td style="padding-left: 40px !important;"><i class="fa fa-caret-right" style="font-size: 20px;margin-top: 8px;position: absolute;margin-left: -18px;" aria-hidden="true"></i><input type="text" class="form-control labour_cost" value="Labour Cost"></td>' +
'<td style="width:10%;"></td>' +
'<td style="width:10%;"></td>' +
'<td style="width:8%;"></td>' +
'<td style="width:12%;"><input type="text" class="form-control item-amount item_dummy" name="amount[]" value="0"/></td>' +
'<td hidden></td>' +
'<td hidden></td>' +
'</tr>';
$('#productItemTable tbody').append(newRow);
initializeSelect2();
// Function to increment class name
function incrementClassName(className) {
var classNumber = parseInt(className.match(/\d+/)[0]);
return className.replace(/\d+/, classNumber + 1);
}
// Initial class name
var initialClassName = 'custom_complaint_class';
var currentClassName;
// Loop to check for existence of subsequent classes
for (var i = 2000; i <= 2100; i++) {
currentClassName = initialClassName + '_' + i;
if ($('.' + currentClassName).length === 0) {
// If the class doesn't exist, increment the last found class
$('.' + initialClassName).removeClass(initialClassName).addClass(currentClassName);
break;
}
}
});
$(document).on('input', '.item_dummy', function() {
var row = $(this).closest('tr');
var labourCostInput = row.prevAll('.custom_complaint_class:first').find('.labour_cost');
var dummyValue = $(this).val();
labourCostInput.val(dummyValue);
});
/** REMOVE ITEMS FROM THE TABLE **/
delete_items_id = [{ 'service': [], 'complaint': [], 'custom_complaint': [] }];
$(document).on('click', '.remove-item', function() {
var $closestTR = $(this).closest('tr');
if($closestTR.attr('class') == "service_class")
{
id = $closestTR.find('input[name="id"]').val();
delete_items_id[0].service.push(id);
console.log(delete_items_id);
}
else if($closestTR.attr('class') == "complaint_class")
{
id = $closestTR.find('input[name="id"]').val();
delete_items_id[0].complaint.push(id);
console.log(delete_items_id);
}
else if($closestTR.attr('class') == "custom_complaint_class")
{
id = $closestTR.find('input[name="id"]').val();
delete_items_id[0].complaint.push(id);
console.log(delete_items_id);
}
while ($closestTR.next().length > 0 && $closestTR.attr('class') != "product") {
if ($closestTR.next().hasClass('service_class') || $closestTR.next().hasClass('complaint_class') || $closestTR.next().hasClass('custom_complaint_class')) {
break;
}
// Remove the next row
$closestTR.next().remove();
}
// Remove the clicked row
$closestTR.remove();
updateCalculations();
});
});
</script>
<script>
$('#addcomplaint').click(function() {
var table = document.getElementById("productItemTable");
var sum = 0;
// Loop through each row
for (var i = 0; i < table.rows.length; i++) {
// Access the 4th cell (index 3) in each row and add its value to the sum
sum += parseInt(table.rows[i].cells[0].textContent);
}
console.log("Sum of 4th row values:", sum);
});
</script>
<script>
// Event listener for removing item
// Event listener for removing item
$(document).on('click', '.remove-item', function() {
var salesOrderProductId = $(this).closest('tr').find('input[name="sales_order_product_id[]"]').val();
// AJAX request to delete the sales order product
$.ajax({
url: '<?php echo base_url()."delete_sales_product"?>',
method: 'POST',
data: { sales_order_product_id: salesOrderProductId },
success: function(response) {
// Check if the deletion was successful
if (response.success) {
// If successful, remove the row from the table
$(this).closest('tr').remove();
updateCalculations(); // Update calculations after removing the row
} else {
// If not successful, display an error message
// alert('Error occurred while deleting the item.');
}
},
error: function(xhr, status, error) {
console.error('Error occurred while deleting the item:', error);
}
});
});
$(document).ready(function() {
// Event listener for customer selection change
$('.vehicle-select').change(function() {
var vehicleId = $(this).val();
if (vehicleId !== '') {
// Find the selected client in the client data
var selectedClient = vehicles.find(function(vehicle) {
return vehicle.vehicle_id == vehicleId;
});
console.log(selectedClient);
$('input[name="client_id"]').val(selectedClient.client_name);
$('input[name="billing_address"]').val(selectedClient.address);
$('input[name="billing_address"]').val(selectedClient.address);
$('input[name="city"]').val(selectedClient.city);
$('input[name="state"]').val(selectedClient.state);
$('input[name="country"]').val(selectedClient.country);
$('input[name="mobile_no"]').val(selectedClient.mobile_no);
$('input[name="postalcode"]').val(selectedClient.postal_code);
}
});
});
</script>
<script>
$(document).ready(function() {
// Event listener for customer selection change
$('.cleint-select').change(function() {
var clientId = $(this).val();
// console.log(vehicleId);
if (clientId !== '') {
// Find the selected client in the client data
var selectedClients = clients.find(function(client) {
return client.client_id == clientId;
});
$('input[id="clientMobile"]').val(selectedClients.mobile_no);
}
});
});
</script>
<script>
// Define the clients array and populate it with data
var vehicles = <?php echo json_encode($vehicle); ?>;
var clients = <?php echo json_encode($client); ?>;
</script>
<script>
function onlyNumbers(event){
var charcode;
charcode = event.which || event.keyCode;
if(charcode>= 48 && charcode <= 57)return true;
return false;
}
</script>
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-beta.1/dist/css/select2.min.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js"></script>
<script>
$(document).ready(function(){
// Initialize select2
$(".SelExample").select2();
});
function initializeSelect2() {
$('.SelExample').select2({
width: '249px' // Adjust width as needed
});
}
</script>
<script>
$(document).ready(function() {
// AJAX request to save client
$('#saveVehcileBtn').click(function() {
var formType = $('#formType').val();
console.log(formType);
var reg_no = $('#reg_no').val();
var model = $('#model').val();
var make = $('#make').val();
var clientName = $('#clientName').val();
var clientMobile = $('#clientMobile').val();
var createclientName = $('#create-clientName').val();
var createclientMobile = $('#create-clientMobile').val();
var createclientType = $('#create-clientType').val();
if (formType == 'select')
{
var ifStatementCondition = "clientName !== '' && clientMobile !== '' && reg_no !== '' && model !== '' && make !== ''";
} else {
var ifStatementCondition = "createclientName !== '' && createclientMobile !== '' && createclientType !== '' && reg_no !== '' && model !== '' && make !== ''";
}
console.log(ifStatementCondition);
if( eval(ifStatementCondition) ){
// Send AJAX request to save the client
$.ajax({
url: '<?php echo base_url().'save_vehicle'?>', // URL to your save_client method
method: 'POST',
data: {
client_id: clientName,
mobile_no: clientMobile,
reg_no:reg_no,
model:model,
make:make,
createclientName:createclientName,
createclientMobile:createclientMobile,
createclientType:createclientType,
formType:formType,
},
success: function(response) {
if (response.success) {
$('#addVehicleModal').modal('hide');
toastr.success("Vehicle saved successfully!");
window.location.reload();
} else {
toastr.warning("Failed to save vehicle. Please try again");
}
},
error: function(xhr, status, error) {
console.error('Error occurred while saving vehicle:', error);
toastr.warning("Failed to save vehicle. Please try again");
}
});
}else{
toastr.warning("Please Fill All Data");
}
});
});
</script>
<script>
$(".SelExample").select2();
// Event listener for change in make select dropdown
$("#make").on('change', function() {
var selected_makes = $(this).val(); // Get an array of selected make IDs
// AJAX request to fetch models based on selected make IDs
$.ajax({
url: '<?= base_url("fetch_models") ?>', // URL to your controller method for fetching models
type: 'POST',
dataType: 'json',
data: { selected_makes: [selected_makes] },
success: function(response) {
// Clear existing options in model select dropdown
$("#model").empty();
$("#model").append('<option value=""> Select a Model </option>');
// Populate model select dropdown with fetched models
$.each(response, function(index, model) {
$("#model").append('<option value="' + model.model_id + '">' + model.model_name + '</option>');
});
// Refresh select2 to reflect changes
$("#model").trigger('change');
},
error: function(xhr, status, error) {
console.error(error); // Log any errors to the console
}
});
});
document.getElementById('reg_no').addEventListener('input', function(event) {
var inputText = event.target.value;
event.target.value = inputText.toUpperCase();
});
</script>
<script>
$(document).on('click', '#createClient', function() {
$('.create').show();
$('.select').hide();
$('#formType').val('create');
$('#clientName').val('');
$('#clientMobile').val('');
});
$(document).on('click', '#selectClient', function() {
$('.select').show();
$('.create').hide();
$('#formType').val('select');
$('#create-clientName').val('');
$('#create-clientMobile').val('');
$('#create-clientType').val('');
});
</script>
<style>
.select2-container--default .select2-results__option--highlighted[aria-selected]{
color:#ffffff;
background: #526dee!important;
}
.select2-container .select2-selection--single{
height: 36px;
border:1px solid #ced4da;
}
.select2-container--default .select2-selection--single .select2-selection__rendered{
line-height: 36px;
}
.select2-container--default .select2-selection--single .select2-selection__arrow{
top:4px;
}
</style>