Magento 2: Submit Form on Checkbox Click – How to Guide

formsjavascriptmagento-2.1magento2

Can someone help me?

I need to know how to send the form checkout/cart/updatePost when clicking on a checkbox. It should include an input field hidden or similar with the name=udpate_cart_action and a value.

When we pulse on:

Update Shopping Cart button

<button type="submit"
    name="update_cart_action"
    data-cart-item-update=""
    value="update_qty"
    title="<?php echo $block->escapeHtml(__('Update Shopping Cart')); ?>" class="action update">
     <span>
          <?php /* @escapeNotVerified */ echo __('Update Shopping Cart'); ?>
     </span>
</button>

We send a param in the request object with the name and value.

But I don't if I must to send this name and value with the checkbox or in the JavaScript…

I have this input type checkbox foreach item

<input id="item_<?php echo $block->escapeHtml($itemId) ?>" name="item[check][<?php echo $block->escapeHtml($itemId) ?>]"  type="checkbox" class="check_item" value="<?php echo $block->escapeHtml($itemId) ?>"

And this code javascript:

<script type="text/javascript">
    $(document).ready(function() {
        $(".check_item").on("change", ":checkbox", function() {
            console.log("check");
        });
    });
</script>

But when I pulse on checkbox and it's status change nothing happens 🙁

UPDATE

Thanks, Philipp Sander your answer was correct. The problem was to add

require(['jquery'], function ($){ //code ]);

<script type="text/javascript">
    require(['jquery'], function ($) {

        $(".check_item").change(function() {
            if(this.checked) {
                $("#update_baa").click();
            } else {

                $("#update_baa").click();
            }
        });

    });

</script>

Thanks!!

Best Answer

$(".check_item").change(function() {
    if(this.checked) {
        //Do stuff
    }
});