我已经在这个系统上工作了一段时间了,我遇到了一个小问题。
我想要做什么:将 id 为“totalentered”的输入字段中输入的所有数据复制到 id 为“totalclasses”的所有输入字段中
发生了什么:有多个 id 为“totalclasses”的字段,是使用 PHP 中的 while 循环生成的。但是,数据仅被复制到 ID 为“totalclasses”的第一个输入字段,其余部分保持不变。
我只是无法弄清楚出了什么问题。 这是我的 HTML+PHP 代码
<input type="text" class="form-control" placeholder="Total Classes Taken" id="totalentered">
<!--PHP Code, deleted because it would make reading this post too tiresome-->
<tr>
<th scope="row"><?=$row['rollnumber']?></th>
<td><?=$row['name']?></td>
<td><?php echo $selectedmonth; ?></td>
<td><input data-parsley-type="digits" type="text" class="form-control" placeholder="Classes Attended" name="attended<?= $cnt; ?>" id="attended"></td>
<td><input data-parsley-type="digits" type="text" class="form-control" placeholder="Total Classes Taken" id="totalclasses" name="totalclasses<?= $cnt; ?>"></td>
<input type="hidden" name="student_id<?= $cnt; ?>" value="<?=$student_id?>">
<input type="hidden" name="testmarks<?= $cnt; ?>" value="0">
<input type="hidden" name="assignmentmarks<?= $cnt; ?>" value="0">
<input type="hidden" name="submitted" value="true">
这是我应该完成这项工作的 JavaScript 代码:
<script type="text/javascript">
$(document).ready(function() {
$('form').parsley();
});
$(function() { // <== Doc Ready
$("#totalentered").change(function() { // When the total number of classes are changed
$('#totalclasses').val(this.value); // copy it over to the individual student for convenience
});
});
</script>
谁能帮我解决一下这个问题吗?提前致谢!
最佳答案
不应有多个具有相同 id 的元素。在 PHP 代码中,将 totalclasses
更改为 class
属性。
然后替换
$('#totalclasses').val(this.value);
与
$('.totalclasses').val(this.value);
来自jQuery docs :
Each id value must be used only once within a document. If more than one element has been assigned the same ID, queries that use that ID will only select the first matched element in the DOM. This behavior should not be relied on, however; a document with more than one element using the same ID is invalid.
关于javascript - 我无法使用 Javascript 将输入字段值复制到多个字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51751368/