Jeff Zivkovic Jeff Zivkovic - 7 months ago 20
Javascript Question

Change the value of many input fields

First Stack Overflow question here. I've read over a dozen questions on similar issues, but none of them quite match the problem that I'm struggling with. My Web App is a "Teacher Gradebook" to keep track of scores for various assignments. The view shows a large table listing students, and their scores. When the user clicks a "Class period" button, the table should change to show the students and scores for the new class period. Using the following code, the input fields will not update:

$scope.changeClassPeriod = function(classPerIndex) {
$scope.currClassPer = classPerIndex;
var thisClassPeriod = $scope.classPeriods[$scope.currClassPer];
for (var i = 0; i < thisClassPeriod.assignments.length; i++) {
$("#head"+i).text(thisClassPeriod.assignments[i].assignmentName);
};
for (var i = 0; i < thisClassPeriod.students.length; i++) {
for (var j = 0; j < thisClassPeriod.assignments.length; j++) {
$($('#scoresheet')[0].rows[i+1].cells[j+2]).val(thisClassPeriod.students[i].scores[j]);
};
};
};


The strange thing is, when I use the "Text" command instead of the "Val" command, the view updates so that all tds show the scores that I expect. The downside is, this approach changes all of the input fields into text fields, so the user can no longer edit them.

$($('#scoresheet')[0].rows[i+1].cells[j+2]).text(thisClassPeriod.students[i].scores[j]);


In a similar question posted elsewhere on Stack Overflow, some other helpers mentioned that unique id is needed for each input field. Is that a problem specific to input fields, but not to text fields?

Answer

If .text() is working and .val() is not working then you are targeting some other element then a input field. Try doing this:

$($('#scoresheet')[0].rows[i+1].cells[j+2]).find('input').val(thisClassPeriod.students[i].scores[j]);

If your rest of the code is fine then this should do the job.