Home > other >  Subtract amount on form submit JavaScript / JQuery
Subtract amount on form submit JavaScript / JQuery

Time:06-29

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:

  • create form
  • get input value
  • subtract used points from user's total amount (for example totalPts = 1000)
  • subtract from cart total value used points, converted into $ (100pts = 1$)

For now, my function looks like this:

    function appendRefferalPoints() {
    const totalPts = 1000;

    // creating form - ok
    $form = $('<form id="refForm"  action></form>');
    $form.append(
        '<input type="text" id="refValue" name="refInput"  >'
    );
    $form.append('<button type="submit" >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

CodePudding user response:

 function appendRefferalPoints() {
 const totalPts = 1000;
 let cartValue=10;
 let discount=0;
 let inputValue = 0;   
    // creating form - ok
    $form = $('<form id="refForm"  ></form>');
    $form.append(
        '<input type="text" id="refValue" name="refInput"   value="100" >'
    );
    $form.append('<button id="btnClick" >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>

  • Related