javascript - 我无法使用 Javascript 将输入字段值复制到多个字段

标签 javascript php html

我已经在这个系统上工作了一段时间了,我遇到了一个小问题。

我想要做什么:将 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/

相关文章:

javascript - 下面是提取一些十六进制数据、解释它并将其打印到 console.log 的代码。它在 'req' 循环中工作,但在外部不工作。为什么?

php - 显示类别的产品

javascript - 为 WordPress 中的多个菜单项提供属性(无 .js)

php - 将自定义实体存储库与 FOSUserBundle 结合使用

html - 使用包装器将列表中的 4 张图像与页面的中心对齐

javascript - 在 Rails 应用程序的移动尺寸屏幕中将图像导航元素对齐为 2 行

javascript - 发电机发电值差异

javascript - 使用 Gulp 4 使用 browserSync 重新加载时,SCSS/JS 更改不会被注意到

javascript - Redux 的行为不正确

javascript - 如何为兄弟文件夹中的文件写入路径?