skip to Main Content

I’m trying to make a button visible only when quantity of items on cart changes (just like on ebay shopping cart). I did it but it doesn’t works as expected link, someone knows an easier or different way to do it??

2

Answers


  1. Try this (jquery):

    <input type="number" name="quantity" min="0" max="99">
    <button id="add" style="display: none;">Add Item</button>
    
    <script
      src="https://code.jquery.com/jquery-3.3.1.min.js"
      integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
      crossorigin="anonymous"></script>
    <script>
    $('input[name="quantity"]').on('change keyup', function(){
        var qty = $(this).val();
      if ($.isNumeric(qty) && qty > 0) {
            $('#add').show();
        } else {
            $('#add').hide();
        }
    });
    </script>
    

    Script is quite self-explanatory. If you need further explain, please comment.

    fiddle: https://jsfiddle.net/qkLfftoo/7/

    Note: This script is to provide better user experience and not meant for validation. Please use back-end validation to ensure entry is not negative integer.

    For multiple buttons:

    <div class="item">
      <input type="number" name="quantity" min="0" max="99">
      <button class="add" data-id="1" style="display: none;">Add Item</button>
    </div>
    <div class="item">
      <input type="number" name="quantity" min="0" max="99">
      <button class="add" data-id="2" style="display: none;">Add Item</button>
    </div>
    <div class="item">
      <input type="number" name="quantity" min="0" max="99">
      <button class="add" data-id="3" style="display: none;">Add Item</button>
    </div>
    $('input[name="quantity"]').on('change keyup', function(){
        var item = $(this).closest('.item');
        var qty = $(this).val();
      if ($.isNumeric(qty) && qty > 0) {
            item.find('.add').show();
        } else {
            item.find('.add').hide();
        }
    });
    
    $('.add').on('click', function(){
        var product_id = $(this).data('id');
      var item = $(this).closest('.item');
      var qty = item.find('input[name="quantity"]').val();
      alert('product_id: ' + product_id + ' * ' + qty + ' will be added');
    });
    

    fiddle: https://jsfiddle.net/qkLfftoo/27/

    Login or Signup to reply.
  2. As it is a front-end development part, you can use jQuery. Using jQuery to disable a button has many advantages as it will allow you to enable and disable the button based on user interaction. You will easily be able to use this code with other jQuery implementations.

    You can check following tutorial for more reference.

    https://blog.revillweb.com/jquery-disable-button-disabling-and-enabling-buttons-with-jquery-5e3ffe669ece

    https://www.formget.com/enable-disable-button-jquery/

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search