-1

如何使用javascript计算一些输入字段?
如果问题对你来说很容易,我真的很抱歉<3

<table>
<tr>
    <td>
    <input name="price_1" id="price_1" value="5" type="text">
    <input name="pieces_1" id="pieces_1" type="text">
    <input name="subtot_1" id="subtot_1" type="text">
    </td>
</tr>
<tr>
    <td>
    <input name="price_2" id="price_2" value="7" type="text">
    <input name="pieces_2" id="pieces_2" type="text">
    <input name="subtot_2" id="subtot_2" type="text">
    </td>
</tr>
<tr>
    <td>
    <input name="price_3" id="price_3" value="9" type="text">
    <input name="pieces_3" id="pieces_3" type="text">
    <input name="subtot_3" id="subtot_3" type="text">
    </td>
</tr>
<tr>
    <td id="total_price">21</td>
</tr>

谢谢大家!

4

1 回答 1

3

嗨 Sanela 我创建了一个演示来帮助你,它使用 jQuery

演示

http://jsfiddle.net/L9PJa/

HTML

<table>
<tr>
    <td>
    <input name="price_1" id="price_1" class="price" value="5" type="text">
    <input name="pieces_1" id="pieces_1" type="text" value="1">
    <input name="subtot_1" id="subtot_1" type="text">
    </td>
</tr>
<tr>
    <td>
    <input name="price_2" id="price_2" class="price" value="7" type="text">
    <input name="pieces_2" id="pieces_2" type="text" value="1">
    <input name="subtot_2" id="subtot_2" type="text">
    </td>
</tr>
<tr>
    <td>
    <input name="price_3" id="price_3" class="price" value="9" type="text">
    <input name="pieces_3" id="pieces_3" type="text" value="1">
    <input name="subtot_3" id="subtot_3" type="text">
    </td>
</tr>
<tr>
    <td id="total_price"></td>
</tr>
<tr>
    <td><input type="button" id="button" value="calculate"></td>
</tr>  

JavaScript

$("#button").click(function() {
  $('#total_price').text('0');
  $(".price").each(function() {
    $(this).next().next().val(parseInt($(this).val())*parseInt($(this).next().val()));
    $('#total_price').text(parseInt($('#total_price').text())+parseInt($(this).next().next().val()));
  });
});

点击动态创建的元素

$("body").on("click", "#button", function() {
   $('#total_price').text('0');
   $(".price").each(function() {
      $(this).next().next().val(parseInt($(this).val())*parseInt($(this).next().val()));
      $('#total_price').text(parseInt($('#total_price').text())+parseInt($(this).next().next().val()));
   });
});

输入不相邻

$("body").on("click", "#button", function() {
   $('#total_price').text('0');
   $(".price").each(function() {
      $(this).next('input').next('input').val(parseInt($(this).val())*parseInt($(this).next('input').val()));
      $('#total_price').text(parseInt($('#total_price').text())+parseInt($(this).next('input').next('input').val()));
   });
});
于 2013-04-19T14:02:19.307 回答