【发布时间】: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" /> <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" /> <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" />
<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