Find Discounts Array

Is there a way to determine the Array of Discounts based on the Base Price initially and then calculate them against the Amount After Discount?

In the image provided below, we have the Base Price. This base price may include multiple discounts.

Each discount should only be applied after the Base Price has been calculated.

My PHP script is as follows;

<tbody>
    <div class="form-group">
        <label class=\"col-sm-3\" style='color: green'><strong>Base Price</strong></label>
        <div class='col-sm-8'>
            <input type='number' class='form-control' id='basePrice' name="basePrice" value='5985'>
        </div>
    </div>
    <?php
    $query = $connect->prepare("SELECT * FROM `manage_customers_discount` WHERE status = 1 AND company_id = '1' AND discount_is_deleted = 0");
    $query->execute();
    $query->store_result();

    $rows = $query->num_rows;
    $rows = $rows + 1;

    $arrayDiscountNumber = 0;
    for ($y = 1; $y < $rows; $y++) { ?>

        <tr id="row<?php echo $y; ?>" class="<?php echo $arrayDiscountNumber; ?>">
            <td style="margin-left:20px;">

                <div class="form-group">

                    <select class="form-control" name="discountName[]" id="discountName<?php echo $y; ?>" onchange="getDiscountData(<?php echo $y; ?>)">
                        <option value="">~~SELECT~~</option>
                        <?php
                            $discountSql = "SELECT * FROM `manage_customers_discount` WHERE status = 1 AND company_id = '1' AND discount_is_deleted = 0 ORDER BY discount_order ASC";
                            $discountData = $connect->query($discountSql);

                            while ($row = $discountData->fetch_array()) {
                                echo "<option value='" . $row['id'] . "' id='changeDiscount" . $row['id'] . "'>" . $row['discount_name'] . "</option>";
                            } // /while

                            ?>
                    </select>
                </div>
            </td>
            <td style="padding-left:20px;">
                <input type="text" name="rateDiscount[]" id="rateDiscount<?php echo $y; ?>" autocomplete="off" disabled="true" class="form-control" />
                <input type="hidden" name="rateDiscountValue[]" id="rateDiscountValue<?php echo $y; ?>" autocomplete="off" class="form-control" />
            </td>
            <td style="padding-left:20px;">
                <input type="text" name="totalDiscount[]" id="totalDiscount<?php echo $y; ?>" autocomplete="off" class="form-control" disabled="true" />
                <input type="hidden" name="totalDiscountValue[]" id="totalDiscountValue<?php echo $y; ?>" autocomplete="off" class="form-control" />
            </td>
            <td style="padding-left:20px;">
                <input type="text" name="amountAfterDiscount[]" id="amountAfterDiscount<?php echo $y; ?>" autocomplete="off" class="form-control" disabled="true" />
                <input type="hidden" name="amountAfterDiscountValue[]" id="amountAfterDiscountValue<?php echo $y; ?>" autocomplete="off" class="form-control" />
            </td>
            <td>

                <button class="btn btn-default removeDiscountRowBtn" type="button" id="removeDiscountRowBtn" onclick="removeDiscountRow(<?php echo $y; ?>)"><i class="glyphicon glyphicon-trash"></i></button>
            </td>
        </tr>
    <?php
        $arrayDiscountNumber++;
    } // /for
    ?>
</tbody>

Considering the screenshot, I computed the base price which gave me the initial Amount after Discount Base Price * 15%. For the second discount, I aim to compute the

First Amount After Discount * 10%
. The same logic applies to subsequent discounts until the final Amount after Discount is displayed in the Sub Discount Amount field.

Here is my JavaScript code,

var subTotalValue = $('#basePrice').val();

$("#rateDiscount" + row).val(response.percentage);
$("#rateDiscountValue" + row).val(response.percentage);

var total = Number(response.percentage) * Number(subTotalValue);
total = total.toFixed(2);
$("#totalDiscount" + row).val(total);
$("#totalDiscountValue" + row).val(total);

var total = Number(subTotalValue) - Number(total);
total = total.toFixed(2);
$("#amountAfterDiscount" + row).val(total);
$("#amountAfterDiscountValue" + row).val(total);

ISSUE: It appears that all percentages are currently being calculated against the Base Price

Answer №1

I managed to find a workaround, though it's not the most elegant one. I thought of sharing it with you because I believe you possess the skills to optimize this code further. I want to emphasize that I'm not a seasoned programmer, so kindly refrain from ridiculing or downvoting my solution. My intention is simply to provide you with an alternative perspective.

Now,

Given the SELECT option in my code snippet

onchange="getDiscountData(<?php echo $y; ?>)"
, I manually verify the row. If row == 1, then the base price should be considered. Otherwise, the first instance of Amount After Discount should be used.

Below is the somewhat messy code snippet:

if(row == 1){
    var subTotalValue = $("#basePrice").val();
    
    $("#rateDiscount"+row).val(response.percentage);
    
    var total = Number(response.percentage) * Number(subTotalValue);
    total = total.toFixed(2);
    $("#totalDiscount"+row).val(total);
    
    var discountAmount = Number(subTotalValue) - Number(total);
    discountAmount = discountAmount.toFixed(2);
    $("#amountAfterDiscount"+row).val(discountAmount);
}
if(row == 2){
    var subTotalValue = $("#amountAfterDiscount"+1).val();
    
    $("#rateDiscount"+row).val(response.percentage);
    
    var total = Number(response.percentage) * Number(subTotalValue);
    total = total.toFixed(2);
    $("#totalDiscount"+row).val(total);
    
    var discountAmount = Number(subTotalValue) - Number(total);
    discountAmount = discountAmount.toFixed(2);
    $("#amountAfterDiscount"+row).val(discountAmount);
}
if(row == 3){
    var subTotalValue = $("#amountAfterDiscount"+2).val();
    
    $("#rateDiscount"+row).val(response.percentage);
    
    var total = Number(response.percentage) * Number(subTotalValue);
    total = total.toFixed(2);
    $("#totalDiscount"+row).val(total);
    
    var discountAmount = Number(subTotalValue) - Number(total);
    discountAmount = discountAmount.toFixed(2);
    $("#amountAfterDiscount"+row).val(discountAmount);
    $("#subDiscountAmount"+row).val(discountAmount);
}

In the event that you need a similar fix, feel free to refine it for optimum performance.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can someone explain the meaning of this code?

Recently, I came across a project where this line of code was used in a jQuery script. I'm not sure of its purpose and would appreciate some help understanding why it was included. If necessary, I can provide the entire function for reference. $("#ta ...

If the button is clicked in jQuery, then perform a specific action; otherwise, execute

hello, I am encountering difficulties in getting this feature to function properly. I am utilizing cropbox to allow users to upload their logos. The issue arises when users do not click on the crop button again; it results in overwriting the existing file ...

Show or hide the sibling element of the current element without using a specific identifier in jQuery

I am looking to make div.edit-button toggle its corresponding sibling div.additionalFieldForm. There are multiple instances of both on the page, so I want to target only the pair that are related within the same group. If a div.edit-button is clicked, the ...

What are some effective ways to slow down the image transitions in a Javascript slideshow?

I am currently developing a slideshow that updates Images, Title, and Description simultaneously based on their Array index. The slideshow is functional BUT, my goal is to achieve a smooth transition to the next/previous Image (... title & descript ...

The function within filereader.onload is not running properly in JavaScript

When working with FileReader to read a file and convert it to base64 for further actions, I encountered an issue. Although I was able to successfully read the file and obtain its base64 representation, I faced difficulties in utilizing this data to trigger ...

Is there a way to simulate the parameters of a method callback from an external dependency in Nodejs

Imagine a scenario where I have the following structure: lib/modules/module1.js var m2 = require('module2'); module.exports = function(){ return { // ... get: function(cb){ m2.someMethod(params, function(error, ...

Guide on how to retrieve the vertex information once an object is loaded using the ObjLoader in Three.js

When using ObjLoader in Three.js to load a *.obj file into my scene, everything works fine. However, I'm uncertain on how to manipulate the object's vertices and indices individually. How can I access the vertices of the loaded *.obj model? Atte ...

Is there a way to place two input fields from different forms side by side on the same line?

Here are two forms extracted from an html page: <form method="get" action="search/s" id="number"> <div style="text-align: center;"> <input type="text" id="regNo" name="regNo" size="30" maxLength="50" > or ...

How to retrieve a JSON item without knowing the name of the parent key

When requesting JSON from Wikipedia's API, the URL is: http://en.wikipedia.org/w/api.php?action=query&prop=description&titles=WTO&prop=extracts&exsentences&explaintext&format=json This is how the response is structured: { ...

Tips for adding responses to input fields in AngularJS

I am looking to populate data into 3 inputs based on the JSON response I receive from my node server. However, despite receiving a response, I am unable to input it into the designated fields. Controller: $scope.edit = function(id, contact) { console.log ...

Transfer files with Ajax without the need for a form tag or submission

I'm trying to send images via AJAX without submitting a form. Normally, when submitting a form I can access the images using $_FILES['images']['tmp_name']; However, when trying to send files, I receive an object FileList in an arra ...

Is it possible to display or hide a spinner within a span using Javascript and AJAX?

When submitting a contact form, I want to display and hide a spinner on the submit button. The spinner should be visible while the form is being submitted and hidden once the submission is complete. Below is the code for my submit button with the spinner: ...

When receiving a GET response after a server crash

Question: I am sending a Get request through Ajax every second and waiting for a response from the server. However, if my application crashes and I keep sending requests every second, I only receive a server timeout error (HTTP status code 502) with no oth ...

Position an HTML canvas at the very top of the webpage

Can someone help me figure out how to align a canvas element to the very top (0, 0) of a webpage? I attempted using margin: 0; padding: 0px;, but it didn't work. There always seems to be some white space at the top that I can't eliminate. ...

Is there a way for me to make the login button redirect to the Dashboard?

I'm currently working on a piece of code where I need to implement some form of validation when the user clicks on the sign-in button. Specifically, I want to ensure that both the username and password fields are not left empty. If this condition is m ...

Encountering Routing Issues in Express.js Following Passport.js Authentication

My authentication setup with Passport.js is pretty straightforward. After the user successfully authenticates, I redirect them to /work like this. app.post('/login', passport.authenticate('local', { successRedirect: '/ ...

Enhancing the model using Sequelize JS

Currently, I am in the process of developing a basic API using Express and Sequelize JS. Recently, I encountered an issue while attempting to update a record with req.School, but no changes seemed to occur. Despite checking the code below thoroughly, I did ...

Vitest encountered an issue fetching a local file

I am currently working on testing the retrieval of a local file. Within my project, there exists a YAML configuration file. During production, the filename may be altered as it is received via a web socket. The code functions properly in production, but ...

I am unable to log in using bcryptjs, but I have successfully been able to register a

Hey there! So I'm diving into Nodejs and I've managed to create a simple login/register API. For password encryption, I'm using bcryptjs. Testing it out on postman, I can successfully register a new user. However, when attempting to login wi ...

Troubleshooting script not detecting changes in form

I am currently implementing a script to detect any changes in the form fields and notify the user if there are any. However, instead of triggering the alert box as intended, a different JavaScript box is displayed. Despite my efforts, the script is not re ...