【问题标题】:Setting a maximum quantity value with Javascript使用 Javascript 设置最大数量值
【发布时间】:2021-02-08 00:32:09
【问题描述】:

我有这个 javascript 来防止数量字段低于 1。我想做的是确保最大数量是 10 并且不能低于 1。

/**
   * When using the quantity selector, this can be used to decrease the quantity (be ensuring it won't be lower than 1)
   */

}, {
  key: '_decreaseQuantity',
  value: function _decreaseQuantity(event, target) {
    target.nextElementSibling.value = Math.max(parseInt(target.nextElementSibling.value) - 1, 1);
  }

  /**
   * When using the quantity selector, this can be used to increase the quantity
   */

}, {
  key: '_increaseQuantity',
  value: function _increaseQuantity(event, target) {
    target.previousElementSibling.value = parseInt(target.previousElementSibling.value) + 1;
  }

  /**
   * Make sure the quantity does not go below when manually changed
   */

}, {
  key: '_validateQuantity',
  value: function _validateQuantity(event, target) {
    target.value = Math.max(parseInt(target.value) || 1, 1);
  }
}]);

【问题讨论】:

    标签: javascript html validation math shopify


    【解决方案1】:

    复制你已经做的以防止值低于 1 就足够了。

    {
      key: '_decreaseQuantity',
      value: function _decreaseQuantity(event, target) {
        target.nextElementSibling.value = Math.max(parseInt(target.nextElementSibling.value) - 1, 1);
      }
    
      /**
       * When using the quantity selector, this can be used to increase the quantity
       */
    
    }, {
      key: '_increaseQuantity',
      value: function _increaseQuantity(event, target) {
        target.previousElementSibling.value = Math.min(parseInt(target.previousElementSibling.value) + 1, 10); // Added check
      }
    
      /**
       * Make sure the quantity does not go below when manually changed
       */
    
    }, {
      key: '_validateQuantity',
      value: function _validateQuantity(event, target) {
        target.value = Math.min(Math.max(parseInt(target.value) || 1, 1), 10); // Added check
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2014-09-08
      • 2019-02-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-30
      相关资源
      最近更新 更多