Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
252 views
in Technique[技术] by (71.8m points)

javascript - How to fix sum of multiple input fields if same class in one <td contenteditable> not <td><input>

I can't sum on table td "jumlah" for "total"

<script>
$(document).on("change", ".jumlah", function() {
    var sum = 0;
    $(".jumlah").each(function(){
        sum += +$(this).val();
    });
    $(".total").val(sum);
});
</script>

<input type="text" id="total" class="total" value=""  />

I expect the output for total from jumlah enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Elements with the [contenteditable] attribute will not have a [value] attribute because:

  1. Only non-interactive, non-void, flow and phrase elements like <div></div>, <section></section>, <spab></span> etc. can have [contenteditable].
  2. Only form controls such as <input>, <textarea>, <output>, etc. can have the [value] attribute.

So instead of .val() use .text() since text is the content between the tags of non-form controls. The important change is a ternary:

if this is an input get its value otherwise get its text

sum += $(this).is('input') ? +$(this).val() : +$(this).text(); 

The minor changes are:

  • input event instead of change because it looks slick.
  • The form is registered to the input event instead of document.

$('.totals').on("input", ".subtotal", function() {
  let sum = 0;
  $(".subtotal").each(function(){
    sum += $(this).is('input') ? +$(this).val() : +$(this).text();
  });
  $(".total").val(sum);
});
:root {font:700 16px/1.2 Consolas}
input, output, data {display:inline-block;font:inherit;text-align:right;width:125px;}
output, data {width:50px}
data {outline:1px solid #aaa;padding:2px 17px 2px 0px;margin:1px 0px 1px 2px;width:110px}
<form class='totals'>
  <table>
  <tr><td><input class="subtotal" type='number' value='0'></td></tr>
  <tr><td><input class="subtotal" type='number' value='0'></td></tr>
  <tr><td><input class="subtotal" type='number' value='0'></td></tr>
  <tr><td><data class="subtotal" contenteditable>0</data></td></tr>
  <tr><td><data class="subtotal" contenteditable>0</data></td></tr>
  <tr><td><data class="subtotal" contenteditable>0</data></td></tr>
  <tr><td>Total: <output class="total">0</output></td></tr>
  </table>
 </form>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...