如何使用jQuery添加输入

时间:2019-06-12 23:22:29

标签: jquery

我用jquery追加了一个内容,所以无论谁单击按钮,都会在其中添加数字的地方添加更多输入,我想对所有这些输入值求和,而且我添加了两个很重要的值

$(document).ready(function() {
  $('#square').on('click', '#add', function() {
    var value = $('#addmore').val();
    var html = value + '<input id="inp3" class="number"><br>';
    $('#secondary').append(html);
  })
  $("#secondary").on("click", "#sum", function() {
    // I WANT HELP HERE
    console.log(total);
  })
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="square">
  <h1>summary</h1>
  <div id="secondary">
    Your daily salary: <input id="salary" type="number" class="inp" placeholder="Enter your daily salary"> <input id="addmore"><button id="add">add more</button><br> Your business income daily <input id="income" type="number" class="inp" placeholder="Enter your daily salary"><br>
    <button id="sum">summarise</button>
    <input type="number" class="gl" readonly>
  </div>
</div>

2 个答案:

答案 0 :(得分:0)

[1] ID应该是唯一的,因此不要对多个元素使用相同的ID。您正在使用id="inp3"和附加输入,因此ID将重复

[2] 您需要遍历输入以获取SUM ..您可以为要求和的所有输入添加相同的类,也可以使用$(".inp , .number")

$(document).ready(function() {
  $('#square').on('click', '#add', function() {
    var value = $('#addmore').val();
    var html = value + '<input class="number"><br>';
    $('#secondary').append(html);
  })
  $("#secondary").on("click", "#sum", function() {
    var total = 0;
    $(".inp , .number").each(function(){
      total += parseInt($(this).val() ? $(this).val() : 0);
    });
    console.log(total);
  })
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="square">
  <h1>summary</h1>
  <div id="secondary">
    Your daily salary: <input id="salary" type="number" class="inp" placeholder="Enter your daily salary"> <input id="addmore"><button id="add">add more</button><br> Your business income daily <input id="income" type="number" class="inp" placeholder="Enter your daily salary"><br>
    <button id="sum">summarise</button>
    <input type="number" class="gl" readonly>
  </div>
</div>

[3] ,我不知道在value

中使用var html = value + '<input class="number"><br>';的目的

答案 1 :(得分:0)

您需要遍历所有.number输入,将这些值加到总计中。

  $("#secondary").on("click", "#sum", function() {
    var total = 0;
    $("#secondary .number").each(function() {
      if (this.value) {
        total += parseInt(this.value);
      }
    }
    console.log(total);
  })