Thursday, 13 April 2017

how to submit a form without knowing a button id/class or form id/class?

Hi i have multiple forms in a single page each of this having different productId which is getting from backend, and each form having 2 buttons one to add product one to remove product. if they click on '+' button it has to go to 'if' condition in javascript, if they click on '-' button it has to go to 'else' condition in javascript

this is my html

<form>
    <input type="hidden" class="form-control" name="productCatalogId" value="<%= data.productDetails[i].productCatalogId %>">
    <input type="hidden" class="form-control" name="productquantity" value="<%= data.productDetails[i].productQuantity %>">
    <button type="button" value="addition" class="btn btn-primary btn-sm">+</button>
    <h4>
        <%= data.productDetails[i].productQuantity %>
    </h4>
    <button type="button" value="substraction" class="btn btn-primary btn-sm">- </button>
</form>

Like this i have number of forms!!

and my javascript

$(':button').click(function(e) {
                e.preventDefault();
                var updateOrder = $(this.form).serializeArray();
                dataObj = {};
                $(updateOrder).each(function(i, field) {
                    dataObj[field.name] = field.value;
                });
                console.log(dataObj['productquantity']);
                var orderId = $("#orderid").val();
                updateOrder.push({
                    name: "orderId",
                    value: orderId,
                });
                // console.log($(':button').val());
                if ($(':button').val() == 'addition') {
                    var quantity = parseInt($("input[name=productquantity]").val()) + 1;
                } else {
                    var quantity = parseInt($("input[name=productquantity]").val()) - 1;
                }
                updateOrder.push({
                    name: "quantity",
                    value: quantity,
                });
                // console.log(updateOrder);
                $.ajax({
                    url: '/order/updateorderitems',
                    type: 'POST',
                    data: updateOrder,
                    success: function(response) {
                        if (response.success) {
                            // console.log(response);
                        }
                    }
                });
                // console.log(productData);
            });

whenever i click on any button it is going to 'if condition' only!! Can anyone please suggest me what i am doing wrong?



via Manoj

No comments:

Post a Comment