JSFiddle - React, Tailwind, and code Playground

by helgatheviking

HTML

<form class="cart">
<div class="nyp">
<div class="error">
Please enter at least 10.
</div>
<label for="nyp">Enter an amount</label>
<input id="nyp" name="nyp" type="text" value=""/>
</div>
<label for="qty">Quantity</label>
<input id="qty" class="qty" type="number" value="0" data-product_id="99">
</form>

CSS

.nyp { display: block; margin-bottom: 1.6em; }
.nyp .error { display: none; color: red; border: 1px solid red; margin-bottom: 1.6em; }

JavaScript

/*
 * One Page Checkout (simplified)
 */

// Quantity buttons add/remove items from cart via AJAX
// Don't actually have a cart here, so just firing a call to a pretend function.
$('form').on('change input', 'input.qty', function(e) {

  var input = $(this);
  var timeout = '';
  
  // Allow 3rd parties to validate and quit early. Proposed triggerHandler().
  if (false === $('body').triggerHandler('opc_validate_add_remove_product', [input])) { 
    e.stopImmediatePropagation();
    input.val(0);
    return false;
  }

  clearTimeout(timeout);

  timeout = setTimeout(function() {

    var data = {
      quantity: input.val(),
      add_to_cart: parseInt(input.data('product_id')),
      nonce: 'some_nonce'
    };

    if (data['quantity'] == 0) {
      data['action'] = 'pp_remove_from_cart';
    } else {
      data['action'] = 'pp_update_add_in_cart';
    }

    input.ajax_add_remove_product(data, e);

  }, 1000);

  e.preventDefault();

});

// Pseudo function that would make an ajax call.
$.fn.ajax_add_remove_product = function(data, e) {
  console.log('ajax call happened');
};


/*
 * Name Your Price (simplified)
 */

// Some kinda listener
/**
 * Validate One Page Checkout ajax add to cart.
 */
$('body').on('opc_validate_add_remove_product', function(e, $triggeredby) {
  console.log('callback');
  var valid = true;

  //	if( 'pp_update_add_in_cart' === data.action ) {
  var $cart = $triggeredby.closest('.cart');
  var $nyp = $cart.find('.nyp');
  var $qty = $cart.find('.qty');

  var num = $nyp.find('input').val();

	/*
  * This is a place where I'm a little stuck.
  * I don't want to validate the amount input when the quantity=0 
  * as that's typically someone removing the item from the cart.
  * But if I don't then this callback returns FALSE on the input listener and TRUE on the change listener.
  * And then the ajax call is fired, the qty is 0 and it tries to remove a product from the cart that isn't in the cart.
  * which returns a funky error. 
  */
  if...