Frosty619 Frosty619 - 4 months ago 6
PHP Question

Unable to get element id dynamically in javascript

I have a list of students that I am looping through and adding to my page. Each student has a unique ID, and when

getStudentInfo
is invoked, it does something with the id. The problem is that whichever student I click, I get back the same id, belonging to student1.

Where am I going wrong?

foreach ($students as $student) {


echo '<tr>';
echo '<td>
'.$student[student_permalink].'
<input type="submit"
value="info"
onclick="getStudentInfo()"
class="student-name-btn"
id="'.$student[student_permalink].'"

/>
</td>';

}


js:

function getStudentInfo() {
var studentLink = $('.student-name-btn').attr('id');
console.log(studentLink);
}

Answer

Your code is selecting all the buttons on the page with that class and than reads the id of the first one in the list. You are not limiting it to the one that was clicked.

What most people would do is add events with jQuery and not inline.

//needs to be loaded after the element or document ready
$(".student-name-btn").on("click", function() {
    console.log(this.id);
});

For yours to work, you would need to pass a reference to the button that was clicked.

onclick="getStudentInfo(this)"

and than change it to use the node passed in

function getStudentInfo(btn) {
    var studentLink = $(btn).attr('id');
    console.log(studentLink);
}
Comments