user19433092
user19433092

Reputation:

Subtract amount on form submit JavaScript / JQuery

I have a checkout page, where I would like to implement a new feature: subtract from total cart value a certain amount, introduced in an input.

Example: There is 1 item in cart, with value of 10.00$. If user typed 100 in that input, then he would have a discount of 1$ (100 pts = 1$ in this example) and the final value of the cart would be 9.00$. Since I'm using some integrated apps for getting/calculating item value, total cart value, etc. I would like to get some generic code, which I would eventually adjust, to link with my existing code, functions, etc.

The function I have should have these features:

For now, my function looks like this:

    function appendRefferalPoints() {
    const totalPts = 1000;

    // creating form - ok
    $form = $('<form id="refForm" class="coupon-form" action></form>');
    $form.append(
        '<input type="text" id="refValue" name="refInput" class="coupon-value input-small" >'
    );
    $form.append('<button type="submit" class="btn">Aplica</button>');
    $("body").append($form);

    // get input value - not ok
    $("#refForm").submit(function () {
        let value = 0;
        $.each($("#refForm").serializeArray(), function (i, field) {
            value[field.name] = field.value;
        });
    });

    // subtraction from totalPts logic - not ok
    let rez = totalPts - value;
    console.log("Final Rez: " + rez);


    // subtraction converted pts from cart value logic


} 

Now when I submit the form I only url changes from /checkout#/cart to /checkout/?refInput=512#/cart

Upvotes: 0

Views: 161

Answers (1)

Madhu
Madhu

Reputation: 76

 function appendRefferalPoints() {
 const totalPts = 1000;
 let cartValue=10;
 let discount=0;
 let inputValue = 0;   
    // creating form - ok
    $form = $('<form id="refForm" class="refForm coupon-form" ></form>');
    $form.append(
        '<input type="text" id="refValue" name="refInput" class="coupon-value input-small"  value="100" >'
    );
    $form.append('<button id="btnClick" class="btn">Aplica</button>');
    $("body").append($form);
    $(document).on("submit", "#refForm", function(e){  
    //getting input value while submitting form
        inputValue=$("#refValue").val();
        //converting 100 pts to 1 dallor
        discount=inputValue/100;
        //calculating balance pts
        let balancePts = totalPts - parseInt(inputValue);
        //calculating final amount
    let finalCartValue=cartValue-discount;
    alert("finalCartValue"+finalCartValue);
    });
 }
appendRefferalPoints();
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

Upvotes: 1

Related Questions