点击按钮填充文本框问题求助:仅填充首个框+值叠加问题
学生评价按钮与文本框交互问题修复
问题分析与修复方案
问题1:仅首个学生文本框响应按钮点击
原因:所有文本框的id均为result,DOM中id必须唯一,document.getElementById("result")只会获取到第一个匹配的元素,导致后续学生的文本框无法被选中。
修复:为每个学生的文本框生成唯一id,用学生的exam_group_class_batch_exam_students_id拼接;同时修改按钮的onclick事件,传递对应学生ID,以便找到目标文本框:
<!-- 修改按钮的onclick事件 --> <input type="button" value="Good" name="no" onclick="moveNumbers(this.value, '<?php echo $student['exam_group_class_batch_exam_students_id']; ?>')"> <input type="button" value="Very Good" name="no" onclick="moveNumbers(this.value, '<?php echo $student['exam_group_class_batch_exam_students_id']; ?>')"> <input type="button" value="Improving" name="no" onclick="moveNumbers(this.value, '<?php echo $student['exam_group_class_batch_exam_students_id']; ?>')"> <!-- 修改文本框的id为唯一值 --> <input type="text" id="result_<?php echo $student['exam_group_class_batch_exam_students_id']; ?>" class="form-control rem1" name="exam_group_student_rem1_<?php echo $student['exam_group_class_batch_exam_students_id']; ?>" value="<?php echo $student['exam_group_exam_result_rem1']; ?>">
问题2:按钮点击值叠加,需保留最后一次点击值
原因:原JS代码将文本框原有值与新点击值拼接,导致内容叠加。
修复:修改JS函数,直接将文本框值设置为当前点击的按钮值,而非累加:
function moveNumbers(num, studentId) { var txtElement = document.getElementById("result_" + studentId); txtElement.value = num; // 直接赋值替换原有内容 }
修改后的完整代码片段
PHP循环部分
<?php if (empty($resultlist)) { ?> <tr> <td colspan="7" class="text-danger text-center"><?php echo $this->lang->line('no_record_found'); ?></td> </tr> <?php } else { foreach ($resultlist as $student) { ?> <tr class="std_adm_<?php echo $student['admission_no']; ?>"> <input type="hidden" name="prev_id[<?php echo $student['exam_group_class_batch_exam_students_id'] ?>]" value="<?php echo $student['exam_group_exam_result_id'] ?>"> <input type="hidden" name="exam_group_student_id[]" value="<?php echo $student['exam_group_class_batch_exam_students_id'] ?>"> <td> <div> <input type="button" value="Good" name="no" onclick="moveNumbers(this.value, '<?php echo $student['exam_group_class_batch_exam_students_id']; ?>')"> <input type="button" value="Very Good" name="no" onclick="moveNumbers(this.value, '<?php echo $student['exam_group_class_batch_exam_students_id']; ?>')"> <input type="button" value="Improving" name="no" onclick="moveNumbers(this.value, '<?php echo $student['exam_group_class_batch_exam_students_id']; ?>')"> </div> </td> <td> <input type="text" id="result_<?php echo $student['exam_group_class_batch_exam_students_id']; ?>" class="form-control rem1" name="exam_group_student_rem1_<?php echo $student['exam_group_class_batch_exam_students_id']; ?>" value="<?php echo $student['exam_group_exam_result_rem1']; ?>"> </td> </tr> <?php } } ?>
JS函数部分
function moveNumbers(num, studentId) { var txtElement = document.getElementById("result_" + studentId); txtElement.value = num; }
内容的提问来源于stack exchange,提问作者Esepebbles
相关产品推荐
相关产品推荐

