【问题标题】:How to get the average of all the dynamic inputs如何获得所有动态输入的平均值
【发布时间】:2020-06-15 01:24:59
【问题描述】:

我找不到所有输入的平均值。我的代码只读取我在 html 中声明的输入,但不读取其他动态的。

这是我的代码:

        $(document).ready(function(){
        // adds a new row
    	$(".addCF").click(function(){
    		$("#customFields").append('<tr valign="top"><th scope="row"><label for="customFieldName">Custom Field</label></th><td><input type="text" class="code" id="customFieldName" name="customFieldName[]" value="" placeholder="Input Name" /> &nbsp; <a href="javascript:void(0);" class="add">Add </a><a href="javascript:void(0);" class="remCF">Remove</a></td></tr>');
        });
        // deletes the row
        $("#customFields").on('click','.remCF',function(){
            $(this).parent().parent().remove();
        });
        $("#customFields").on('click','.add',function(){
          $("#customFields").append('<tr valign="top"><th scope="row"><label for="customFieldName">Custom Field</label></th><td><input type="text" class="code" id="customFieldName" name="customFieldName[]" value="" placeholder="Input Name" /> &nbsp; <a href="javascript:void(0);" class="add">Add </a><a href="javascript:void(0);" class="remCF">Remove</a></td></tr>');
        });
        $("#click").click(function(){
            var isbn = document.getElementById('customFieldName').value;
            alert(isbn / $("input").length)
            $("#averageGrade").text("Average Grade: " + isbn)
        })
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="form-table" id="customFields">
    	<tr valign="top">
    		<th scope="row"><label for="customFieldName">Custom Field</label></th>
    		<td>
    			<input type="text" class="code" id="customFieldName" name="customFieldName[]" placeholder="Input Name" /> &nbsp;
    			<a href="javascript:void(0);" class="addCF">Add</a>
            </td>
        </tr>
    </table>
    <button id = "click" class = "btn btn-primary" >Hi</button>
    <p id = "averageGrade">Average Grade:</p>

请帮忙! 谢谢!

【问题讨论】:

  • 您拥有多个具有相同 id 的元素。你应该改用一个类。
  • 这是一个选择器问题。您将按 ID 进行操作,这意味着您的函数仅查找该 ID 的直接实例,然后停止查找。你需要的是一个类,遍历值并计算你的平均值。

标签: javascript html jquery function input


【解决方案1】:

每个element.id 必须是唯一的 - 请将customFieldName 更改为一个类,然后遍历输入并计算平均值。此外,您可以为所有“添加”按钮重用同一个类,并将该字符串保存在一个变量中,这样您就不必paste it multiple times

let inputTemplate = '<tr valign="top"><th scope="row"><label>Custom Field</label></th><td><input type="text" class="customFieldName code" name="customFieldName[]" value="" placeholder="Input Name" /> &nbsp; <a href="javascript:void(0);" class="addCF">Add </a><a href="javascript:void(0);" class="remCF">Remove</a></td></tr>';

$(document).ready(function() {
  
  // adds a new row
  $("#customFields").on('click', '.addCF', function() {
    $("#customFields").append(inputTemplate);
  });

  // deletes the row
  $("#customFields").on('click', '.remCF', function() {
    $(this).parent().parent().remove();
  });

  $("#click").click(function() {

    let fields = $('.customFieldName'),
        total = 0;
        
    for (let field of fields)
      total += Number(field.value);
      
    let average = total / fields.length;
    $("#averageGrade").text("Average Grade: " + average);
    
  })
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="form-table" id="customFields">
  <tr valign="top">
    <th scope="row"><label>Custom Field</label></th>
    <td>
      <input type="text" class="customFieldName code" name="customFieldName[]" placeholder="Input Name" /> &nbsp;
      <a href="javascript:void(0);" class="addCF">Add</a>
    </td>
  </tr>
</table>
<button id="click" class="btn btn-primary">Hi</button>
<p id="averageGrade">Average Grade:</p>

【讨论】:

    【解决方案2】:

    首先,您需要一种选择所有字段的方法。由于id 必须(应该)是唯一的,您可以使用名称或类.code 并删除id="customFieldName"

    然后,getElementById,顾名思义,返回一个元素。你需要全选!如果你使用类名,你可以使用getElementsByClassName,或querySelectorAll,或者,因为你已经在使用jQuery,只需$(".code"),以及一个读取每个输入值的循环(如果你使用jQuery,你也可以使用each())。

    var sum=0,count=0,average;
    $(".code").each(function() {
        var value=parseInt($(this).val());
        //You may want to validate the field
        if(!isNaN(value)) sum+=value;
        count++;
    });
    average=sum/count;
    ...
    

    【讨论】:

      【解决方案3】:

      正如许多人所指出的(包括我在评论部分中),您将使用错误的选择器。 id 是一个独特的选择器,这意味着脚本将查看id 的第一个实例,然后立即停止。

      您需要做的是使用一个选择器来遍历其实例的每一次出现。这就是存在class 选择器的原因。这将是您代码中的第一个修复程序。

      我个人如何计算平均值是创建一个数组并将push(); 成绩的值放入数组中。我们还需要做一个parseInt() 以确保我们的值实际上是作为numbers 处理的。否则,它们将被解释为strings

      然后您需要遍历数组,将值相加并除以数组的长度。

      HTML 示例:

      <div class="row">
          <div class="col-12">
              <table class="table form-table" id="customFields">
                  <tr valign="top">
                      <th scope="row"><label>Custom Field</label></th>
                      <td>
                          <input type="number" class="customFieldName" placeholder="Input Number" /> &nbsp;
                          <a href="javascript:void(0);" class="addCF">Add</a>
                      </td>
                  </tr>
              </table>
          </div>
      </div>
      <div class="row">
          <div class="col-md-4">
              <button id="calcAvrgBtn" class="btn-primary">Calculate average grade</button>
          </div>
          <div class="col-md-4">
              <p id="averageCalc"></p>
          </div>
      </div>
      

      jQuery 示例:

      $('.addCF').on("click", function() {
          $("#customFields").append('<tr valign="top"><th scope="row"><label>Custom Field</label></th><td><input type="number" class="customFieldName" placeholder="Input Number" /> &nbsp; <a href="javascript:void(0);" class="remCF">Remove</a></td></tr>');
      });
      
      $(document).on("click", "a.remCF" , function() {
          $(this).parent().parent().remove();
      });
      
      $('#calcAvrgBtn').on("click", function() {
          let gradeArr = [];
      
          $('.customFieldName').each(function() {
              gradeArr.push(parseInt($(this).val()));
          });
      
          let total = 0;
      
          for(var i = 0; i < gradeArr.length; i++) {
              total += gradeArr[i];
          }
      
          let avg = total / gradeArr.length;
      
          $('#averageCalc').text("The average grade is: "+avg);
      });
      

      Codepen 示例可以在here 找到。

      片段示例:

      $('.addCF').on("click", function() {
      	$("#customFields").append('<tr valign="top"><th scope="row"><label>Custom Field</label></th><td><input type="number" class="customFieldName" placeholder="Input Number" /> &nbsp; <a href="javascript:void(0);" class="remCF">Remove</a></td></tr>');
      });
      
      $(document).on("click", "a.remCF" , function() {
      	$(this).parent().parent().remove();
      });
      
      $('#calcAvrgBtn').on("click", function() {
      	let gradeArr = [];
      	
      	$('.customFieldName').each(function() {
      		gradeArr.push(parseInt($(this).val()));
      	});
      
      	let total = 0;
      	
      	for(var i = 0; i < gradeArr.length; i++) {
      		total += gradeArr[i];
      	}
      	
      	let avg = total / gradeArr.length;
      	
      	$('#averageCalc').text("The average grade is: "+avg);
      });
      <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet"/>
      <div class="row">
      	<div class="col-12">
      		<table class="table form-table" id="customFields">
      			<tr valign="top">
      				<th scope="row"><label>Custom Field</label></th>
      				<td>
      					<input type="number" class="customFieldName" placeholder="Input Number" /> &nbsp;
      					<a href="javascript:void(0);" class="addCF">Add</a>
      				</td>
      			</tr>
      		</table>
      	</div>
      </div>
      <div class="row">
      	<div class="col-md-4">
      		<button id="calcAvrgBtn" class="btn-primary">Calculate average grade</button>
      	</div>
      	<div class="col-md-4">
      		<p id="averageCalc"></p>
      	</div>
      </div>

      【讨论】:

        猜你喜欢
        • 2012-03-18
        • 1970-01-01
        • 2023-02-17
        • 2021-02-17
        • 1970-01-01
        • 2022-08-14
        • 2015-05-03
        • 2020-10-11
        • 1970-01-01
        相关资源
        最近更新 更多