Home > Back-end >  alt attribute keeps getting assigned to last index of nested javascript object
alt attribute keeps getting assigned to last index of nested javascript object

Time:10-07

So I have a series of various JSON objects representing a college class with nested data inside each of them. Each of these objects are stored in an array called classes. Here is an example of how one of the class objects is formatted:

let class_A = {
    professor: "Joey Smith",
    numberStudents: 25,
    courseCode: "COMS 2360",
    seating: {
        "FirstRow": {
            0: {
                firstName: "Sarah",
                collegeMajor: "English",
            },
            1: {
                firstName: "Bob",
                collegeMajor: "Computer Engineering",
            },
            2: { 
                firstName: "Dylan",
                collegeMajor: "Mathematics",
            }
        },
        "SecondRow": {
            3: {
                firstName: "Molly",
                collegeMajor: "Music"
            }
        }
    }
};

Basically, I have a page with all students across all class objects laid out on a page with an add button next to each name, and the add button will eventually allow me to add students to certain groups for assignments, etc.

The page right now with only class_A would looks something like this:

enter image description here

I displayed the student names and the add button next to each student using code like this:

function loadStudents(){
    let page = document.getElementById('page');
    page.innerHTML = "";
    for(seatRow in class.seating){
        for(index in class.seating[seatRow]){
            let studentName = class.seating[seatRow][index].studentName;
            page.innerHTML  = "<p> Name:"   studentName   " <img src='addButImg.png' id = 'addButton' onclick = 'addStudentToGroup()'></p>";
            let addButton = document.getElementById("addButton");
            addButton.alt = studentName;
            console.log(addButton.alt);
        }
    }
}

function addStudentToGroup(){
    let addButton = document.getElementById("addButton");
    console.log(addButton.alt);
}

My page displays correctly like the picture, but I'm having trouble printing the name of the specific student I add to a group when I click on the add button next to the student's name. I assign the add button's alt value to the student's name, and tested it by doing "console.log(addButton.alt)" which prints:

Sarah
Bob
Dylan
Molly

If I click on the first add button, it should trigger the addStudentToGroup() function and print "Sarah" to the console. However, clicking on all the buttons seems to only print the last name in the list of students which is "Molly" regardless of whichever student the button is located next to. The alt seems to get saved as whatever the last student is, and I'm struggling to change the alt value based on whatever student's name I choose to click add for. Does anyone know how to fix this? Any help would be appreciated!

CodePudding user response:

The problem is that all of the buttons have the same id "addButton", so when you try to get the button in addStudentToGroup it retrieves the last item with matching id.

Try sending a reference to the button as argument to addStudentToGroup:

onclick = 'addStudentToGroup(this)'

Try the following:

let classes = [class_A, class_B, class_C, class_D];
let classesAvailable = document.getElementById('classes');
let class = classes[classesAvailable.value];

function loadStudents(){
    let page = document.getElementById('page');
    page.innerHTML = "";
    for(seatRow in class.seating){
        for(index in class.seating[seatRow]){
            let studentName = class.seating[seatRow][index].studentName;
            page.innerHTML  = "<p> Name:"   studentName   " <img src='addButImg.png' id = 'addButton' onclick = 'addStudentToGroup(this)'></p>";
            let addButton = document.getElementById("addButton");
            addButton.alt = studentName;
            console.log(addButton.alt);
        }
    }
}

function addStudentToGroup(buttonEl){
    console.log(buttonEl.alt);
}

CodePudding user response:

You are assigning the same id addButton to all images. If you just want studentName then just pass it in onclick function. like using template literal addStudentToGroup('${studentName}')

let class_A = {professor:"Joey Smith",numberStudents:25,courseCode:"COMS 2360",seating:{"FirstRow":{0:{firstName:"Sarah",collegeMajor:"English",},1:{firstName:"Bob",collegeMajor:"Computer Engineering",},2:{firstName:"Dylan",collegeMajor:"Mathematics",}},"SecondRow":{3:{firstName:"Molly",collegeMajor:"Music"}}}};

loadStudents();

function loadStudents(){
    let page = document.getElementById('page');
    page.innerHTML = "";
    for(seatRow in class_A.seating){
        for(index in class_A.seating[seatRow]){
        //console.log(class_A.seating[seatRow][index]);
            let studentName = class_A.seating[seatRow][index].firstName;
            page.innerHTML  = `<p> Name: ${studentName} <img src="addButImg.png" onclick = "addStudentToGroup('${studentName}')"></p>`;
            //let addButton = document.getElementById("addButton");
            //addButton.alt = studentName;
            // console.log(addButton.alt);
        }
    }
}

function addStudentToGroup(sname){
    console.log(sname);
}
<div id="page">
</div>

  • Related