Ad

Make Button Visible If Text Changes

- 1 answer

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??

Ad

Answer

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/

Ad
source: stackoverflow.com
Ad