字段值相乘

时间:2018-08-24 07:38:57

标签: javascript jquery html

考虑以下代码,我想计算价格和数量字段的乘积。

每次单击更新按钮时,都会显示NAN。

对于数量字段,我使用了加号和减号按钮来增加/减少数量。

我实际上不知道如何调试此特定问题。

$('.btn-number').click(function(e) {
  e.preventDefault();

  fieldName = $(this).attr('data-field');
  type = $(this).attr('data-type');
  var input = $("input[name='" + fieldName + "']");
  var currentVal = parseInt(input.val());
  if (!isNaN(currentVal)) {
    if (type == 'minus') {

      if (currentVal > input.attr('min')) {
        input.val(currentVal - 1).change();
      }
      if (parseInt(input.val()) == input.attr('min')) {
        $(this).attr('disabled', true);
      }

    } else if (type == 'plus') {

      if (currentVal < input.attr('max')) {
        input.val(currentVal + 1).change();
      }
      if (parseInt(input.val()) == input.attr('max')) {
        $(this).attr('disabled', true);
      }

    }
  } else {
    input.val(0);
  }
});
$('.input-number').focusin(function() {
  $(this).data('oldValue', $(this).val());
});
$('.input-number').change(function() {

  minValue = parseInt($(this).attr('min'));
  maxValue = parseInt($(this).attr('max'));
  valueCurrent = parseInt($(this).val());

  name = $(this).attr('name');
  if (valueCurrent >= minValue) {
    $(".btn-number[data-type='minus'][data-field='" + name + "']").removeAttr('disabled')
  } else {

    $(this).val($(this).data('oldValue'));
  }
  if (valueCurrent <= maxValue) {
    $(".btn-number[data-type='plus'][data-field='" + name + "']").removeAttr('disabled')
  } else {

    $(this).val($(this).data('oldValue'));
  }


});
$(".input-number").keydown(function(e) {
  // Allow: backspace, delete, tab, escape, enter and .
  if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 190]) !== -1 ||
    // Allow: Ctrl+A
    (e.keyCode == 65 && e.ctrlKey === true) ||
    // Allow: home, end, left, right
    (e.keyCode >= 35 && e.keyCode <= 39)) {
    // let it happen, don't do anything
    return;
  }
  // Ensure that it is a number and stop the keypress
  if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
    e.preventDefault();
  }
});


function calculate() {
  var num1 = document.getElementById('PPRICE').value;
  var num2 = document.getElementById('QTY').value;
  var update = num1 * num2;
  document.getElementById("TOTAL").innerHTML = update;


}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table cellspacing="0" class="shop_table cart">
  <thead>
    <tr>
      <th class="product-id">Product Id</th>
      <th class="product-name">Product</th>
      <th class="product-price">Price</th>
      <th class="product-quantity">Quantity</th>
      <th class="product-subtotal">Total</th>
      <th class="product-remove">&nbsp;</th>
    </tr>
  </thead>
  <tbody>
    <tr class="cart_item">
      <td class="product-id" valign="center">
        <a title="Remove this item" class="remove" href="#">P521</a>
      </td>
      <td class="product-name" valign="middle">
        <a href="single-product.html">Ship Your Idea</a>
      </td>

      <td class="product-price" valign="middle">
        <span id="PPRICE" class="amount" value="15">$15.00</span>
      </td>

      <td class="product-quantity">
        <div class="quantity buttons_added">
          <input type="button" class="minus btn-number" value="-" data-type="minus" data-field="num">
          <input type="number" id="QTY" name="num" value="0" min="0" max="5" class="input-text qty text input-number" title="Qty">
          <input type="button" class="plus btn-number" value="+" data-type="plus" data-field="num"> &nbsp;ea.
        </div>

      </td>



      <td class="product-subtotal" valign="middle">
        <span id="TOTAL" class="amount">$15.00</span>
      </td>
      <td class="product-remove">
        <a title="Remove this item" class="remove" href="#">
          <span class="glyphicon glyphicon-trash"></span>
        </a>
      </td>
    </tr>
    <tr>
      <td class="actions" colspan="7">
        <div class="coupon" style="display: none;">
          <label for="coupon_code">Coupon:</label>
          <input type="text" placeholder="Coupon code" value="" id="coupon_code" class="input-text" name="coupon_code">
          <input type="submit" value="Apply Coupon" name="apply_coupon" class="button">
        </div>
        <input type="button" id="update" value="Update Cart" name="update_cart" class="button" onClick="calculate()">

      </td>
    </tr>
  </tbody>
</table>

4 个答案:

答案 0 :(得分:2)

span没有value属性。更重要的是,作为Javascript DOM对象,span没有value属性(可以通过Javascript添加,但这只会使事情变得更加困难)。

请使用data-value属性。 data-属性已作为通用属性引入 any HTML元素上。

您可以自由命名数据属性,只要它们的名称以data-开头即可。在您的示例中,您也可以将其命名为data-price并使用PPRICE.dataset.price进行访问。请注意,如果您使用的名称中带有多个破折号(例如data-product-price),则破折号会在元素(dataset)的PPRICE.dataset.productPrice上自动转换为驼峰格式。

$('.btn-number').click(function(e) {
  e.preventDefault();

  fieldName = $(this).attr('data-field');
  type = $(this).attr('data-type');
  var input = $("input[name='" + fieldName + "']");
  var currentVal = parseInt(input.val());
  if (!isNaN(currentVal)) {
    if (type == 'minus') {

      if (currentVal > input.attr('min')) {
        input.val(currentVal - 1).change();
      }
      if (parseInt(input.val()) == input.attr('min')) {
        $(this).attr('disabled', true);
      }

    } else if (type == 'plus') {

      if (currentVal < input.attr('max')) {
        input.val(currentVal + 1).change();
      }
      if (parseInt(input.val()) == input.attr('max')) {
        $(this).attr('disabled', true);
      }

    }
  } else {
    input.val(0);
  }
});
$('.input-number').focusin(function() {
  $(this).data('oldValue', $(this).val());
});
$('.input-number').change(function() {

  minValue = parseInt($(this).attr('min'));
  maxValue = parseInt($(this).attr('max'));
  valueCurrent = parseInt($(this).val());

  name = $(this).attr('name');
  if (valueCurrent >= minValue) {
    $(".btn-number[data-type='minus'][data-field='" + name + "']").removeAttr('disabled')
  } else {

    $(this).val($(this).data('oldValue'));
  }
  if (valueCurrent <= maxValue) {
    $(".btn-number[data-type='plus'][data-field='" + name + "']").removeAttr('disabled')
  } else {

    $(this).val($(this).data('oldValue'));
  }


});
$(".input-number").keydown(function(e) {
  // Allow: backspace, delete, tab, escape, enter and .
  if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 190]) !== -1 ||
    // Allow: Ctrl+A
    (e.keyCode == 65 && e.ctrlKey === true) ||
    // Allow: home, end, left, right
    (e.keyCode >= 35 && e.keyCode <= 39)) {
    // let it happen, don't do anything
    return;
  }
  // Ensure that it is a number and stop the keypress
  if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
    e.preventDefault();
  }
});


function calculate() {
  var num1 = document.getElementById('PPRICE').dataset.value;
  var num2 = document.getElementById('QTY').value;
  var update = num1 * num2;
  document.getElementById("TOTAL").innerHTML = `$ ${update.toFixed(2)}`;


}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table cellspacing="0" class="shop_table cart">
  <thead>
    <tr>
      <th class="product-id">Product Id</th>
      <th class="product-name">Product</th>
      <th class="product-price">Price</th>
      <th class="product-quantity">Quantity</th>
      <th class="product-subtotal">Total</th>
      <th class="product-remove">&nbsp;</th>
    </tr>
  </thead>
  <tbody>
    <tr class="cart_item">
      <td class="product-id" valign="center">
        <a title="Remove this item" class="remove" href="#">P521</a>
      </td>
      <td class="product-name" valign="middle">
        <a href="single-product.html">Ship Your Idea</a>
      </td>

      <td class="product-price" valign="middle">
        <span id="PPRICE" class="amount" data-value="15">$15.00</span>
      </td>

      <td class="product-quantity">
        <div class="quantity buttons_added">
          <input type="button" class="minus btn-number" value="-" data-type="minus" data-field="num">
          <input type="number" id="QTY" name="num" value="0" min="0" max="5" class="input-text qty text input-number" title="Qty">
          <input type="button" class="plus btn-number" value="+" data-type="plus" data-field="num"> &nbsp;ea.
        </div>

      </td>



      <td class="product-subtotal" valign="middle">
        <span id="TOTAL" class="amount">$15.00</span>
      </td>
      <td class="product-remove">
        <a title="Remove this item" class="remove" href="#">
          <span class="glyphicon glyphicon-trash"></span>
        </a>
      </td>
    </tr>
    <tr>
      <td class="actions" colspan="7">
        <div class="coupon" style="display: none;">
          <label for="coupon_code">Coupon:</label>
          <input type="text" placeholder="Coupon code" value="" id="coupon_code" class="input-text" name="coupon_code">
          <input type="submit" value="Apply Coupon" name="apply_coupon" class="button">
        </div>
        <input type="button" id="update" value="Update Cart" name="update_cart" class="button" onClick="calculate()">

      </td>
    </tr>
  </tbody>
</table>

答案 1 :(得分:1)

正如@connexo所指出的,span名义上没有value属性,但是您仍然可以使用getAttribute获得该值:

var num1 = document.getElementById('PPRICE').getAttribute('value');

答案 2 :(得分:1)

您的代码几乎没有问题:

  • 您需要获取value元素的<span>属性值,因此,使用Javascript时,您需要使用attributes.value.value来实现,其中,中间属性中的value是属性的名称,在您的情况下为value
  • 由于您要乘以它。通过隐式类型转换将值转换为数值。

$('.btn-number').click(function(e) {
  e.preventDefault();

  fieldName = $(this).attr('data-field');
  type = $(this).attr('data-type');
  var input = $("input[name='" + fieldName + "']");
  var currentVal = parseInt(input.val());
  if (!isNaN(currentVal)) {
    if (type == 'minus') {

      if (currentVal > input.attr('min')) {
        input.val(currentVal - 1).change();
      }
      if (parseInt(input.val()) == input.attr('min')) {
        $(this).attr('disabled', true);
      }

    } else if (type == 'plus') {

      if (currentVal < input.attr('max')) {
        input.val(currentVal + 1).change();
      }
      if (parseInt(input.val()) == input.attr('max')) {
        $(this).attr('disabled', true);
      }

    }
  } else {
    input.val(0);
  }
});
$('.input-number').focusin(function() {
  $(this).data('oldValue', $(this).val());
});
$('.input-number').change(function() {

  minValue = parseInt($(this).attr('min'));
  maxValue = parseInt($(this).attr('max'));
  valueCurrent = parseInt($(this).val());

  name = $(this).attr('name');
  if (valueCurrent >= minValue) {
    $(".btn-number[data-type='minus'][data-field='" + name + "']").removeAttr('disabled')
  } else {

    $(this).val($(this).data('oldValue'));
  }
  if (valueCurrent <= maxValue) {
    $(".btn-number[data-type='plus'][data-field='" + name + "']").removeAttr('disabled')
  } else {

    $(this).val($(this).data('oldValue'));
  }


});
$(".input-number").keydown(function(e) {
  // Allow: backspace, delete, tab, escape, enter and .
  if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 190]) !== -1 ||
    // Allow: Ctrl+A
    (e.keyCode == 65 && e.ctrlKey === true) ||
    // Allow: home, end, left, right
    (e.keyCode >= 35 && e.keyCode <= 39)) {
    // let it happen, don't do anything
    return;
  }
  // Ensure that it is a number and stop the keypress
  if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
    e.preventDefault();
  }
});


function calculate() {
  var num1 = document.getElementById('PPRICE').attributes.value.value;
  var num2 = document.getElementById('QTY').value;
  var update = num1  * num2;
  document.getElementById("TOTAL").innerHTML = update;


}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table cellspacing="0" class="shop_table cart">
  <thead>
    <tr>
      <th class="product-id">Product Id</th>
      <th class="product-name">Product</th>
      <th class="product-price">Price</th>
      <th class="product-quantity">Quantity</th>
      <th class="product-subtotal">Total</th>
      <th class="product-remove">&nbsp;</th>
    </tr>
  </thead>
  <tbody>
    <tr class="cart_item">
      <td class="product-id" valign="center">
        <a title="Remove this item" class="remove" href="#">P521</a>
      </td>
      <td class="product-name" valign="middle">
        <a href="single-product.html">Ship Your Idea</a>
      </td>

      <td class="product-price" valign="middle">
        <span id="PPRICE" class="amount" value="15">$15.00</span>
      </td>

      <td class="product-quantity">
        <div class="quantity buttons_added">
          <input type="button" class="minus btn-number" value="-" data-type="minus" data-field="num">
          <input type="number" id="QTY" name="num" value="0" min="0" max="5" class="input-text qty text input-number" title="Qty">
          <input type="button" class="plus btn-number" value="+" data-type="plus" data-field="num"> &nbsp;ea.
        </div>

      </td>



      <td class="product-subtotal" valign="middle">
        <span id="TOTAL" class="amount">$15.00</span>
      </td>
      <td class="product-remove">
        <a title="Remove this item" class="remove" href="#">
          <span class="glyphicon glyphicon-trash"></span>
        </a>
      </td>
    </tr>
    <tr>
      <td class="actions" colspan="7">
        <div class="coupon" style="display: none;">
          <label for="coupon_code">Coupon:</label>
          <input type="text" placeholder="Coupon code" value="" id="coupon_code" class="input-text" name="coupon_code">
          <input type="submit" value="Apply Coupon" name="apply_coupon" class="button">
        </div>
        <input type="button" id="update" value="Update Cart" name="update_cart" class="button" onClick="calculate()">

      </td>
    </tr>
  </tbody>
</table>

答案 3 :(得分:1)

这是解决问题的方法。

您从输入中读取的值与从跨度中读取的值不同。

var num1 = document.getElementById('PPRICE').innerHTML;  // span
var num2 = document.getElementById('QTY').value;         // input

此外,由于跨度中包含$,因此这不是一个数字,这就是为什么您收到NaN错误消息的原因。在我的代码中,首先使用此num1 = parseInt(num1.replace('$', ''));清除输入 它将删除$符号,并使用parseInt()函数将var转换为整数。

然后,您可以适当地将结果相乘。最后,我使用以下命令再次添加$。

document.getElementById("TOTAL").innerHTML = '$' + update;

$('.btn-number').click(function(e) {
  e.preventDefault();

  fieldName = $(this).attr('data-field');
  type = $(this).attr('data-type');
  var input = $("input[name='" + fieldName + "']");
  var currentVal = parseInt(input.val());
  if (!isNaN(currentVal)) {
    if (type == 'minus') {

      if (currentVal > input.attr('min')) {
        input.val(currentVal - 1).change();
      }
      if (parseInt(input.val()) == input.attr('min')) {
        $(this).attr('disabled', true);
      }

    } else if (type == 'plus') {

      if (currentVal < input.attr('max')) {
        input.val(currentVal + 1).change();
      }
      if (parseInt(input.val()) == input.attr('max')) {
        $(this).attr('disabled', true);
      }

    }
  } else {
    input.val(0);
  }
});
$('.input-number').focusin(function() {
  $(this).data('oldValue', $(this).val());
});
$('.input-number').change(function() {

  minValue = parseInt($(this).attr('min'));
  maxValue = parseInt($(this).attr('max'));
  valueCurrent = parseInt($(this).val());

  name = $(this).attr('name');
  if (valueCurrent >= minValue) {
    $(".btn-number[data-type='minus'][data-field='" + name + "']").removeAttr('disabled')
  } else {

    $(this).val($(this).data('oldValue'));
  }
  if (valueCurrent <= maxValue) {
    $(".btn-number[data-type='plus'][data-field='" + name + "']").removeAttr('disabled')
  } else {

    $(this).val($(this).data('oldValue'));
  }


});
$(".input-number").keydown(function(e) {
  // Allow: backspace, delete, tab, escape, enter and .
  if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 190]) !== -1 ||
    // Allow: Ctrl+A
    (e.keyCode == 65 && e.ctrlKey === true) ||
    // Allow: home, end, left, right
    (e.keyCode >= 35 && e.keyCode <= 39)) {
    // let it happen, don't do anything
    return;
  }
  // Ensure that it is a number and stop the keypress
  if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
    e.preventDefault();
  }
});


function calculate() {
  var num1 = document.getElementById('PPRICE').innerHTML;
  var num2 = document.getElementById('QTY').value;
  num1 = parseInt(num1.replace('$', ''));
  var update = num1 * num2;
  document.getElementById("TOTAL").innerHTML = '$' + update;


}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table cellspacing="0" class="shop_table cart">
  <thead>
    <tr>
      <th class="product-id">Product Id</th>
      <th class="product-name">Product</th>
      <th class="product-price">Price</th>
      <th class="product-quantity">Quantity</th>
      <th class="product-subtotal">Total</th>
      <th class="product-remove">&nbsp;</th>
    </tr>
  </thead>
  <tbody>
    <tr class="cart_item">
      <td class="product-id" valign="center">
        <a title="Remove this item" class="remove" href="#">P521</a>
      </td>
      <td class="product-name" valign="middle">
        <a href="single-product.html">Ship Your Idea</a>
      </td>

      <td class="product-price" valign="middle">
        <span id="PPRICE" class="amount" value="15">$15.00</span>
      </td>

      <td class="product-quantity">
        <div class="quantity buttons_added">
          <input type="button" class="minus btn-number" value="-" data-type="minus" data-field="num">
          <input type="number" id="QTY" name="num" value="0" min="0" max="5" class="input-text qty text input-number" title="Qty">
          <input type="button" class="plus btn-number" value="+" data-type="plus" data-field="num"> &nbsp;ea.
        </div>

      </td>



      <td class="product-subtotal" valign="middle">
        <span id="TOTAL" class="amount">$15.00</span>
      </td>
      <td class="product-remove">
        <a title="Remove this item" class="remove" href="#">
          <span class="glyphicon glyphicon-trash"></span>
        </a>
      </td>
    </tr>
    <tr>
      <td class="actions" colspan="7">
        <div class="coupon" style="display: none;">
          <label for="coupon_code">Coupon:</label>
          <input type="text" placeholder="Coupon code" value="" id="coupon_code" class="input-text" name="coupon_code">
          <input type="submit" value="Apply Coupon" name="apply_coupon" class="button">
        </div>
        <input type="button" id="update" value="Update Cart" name="update_cart" class="button" onClick="calculate()">

      </td>
    </tr>
  </tbody>
</table>