Issue
HTML:
<table>
<tr>
<th>Student Name</th>
<th>Student Grades</th>
</tr>
<tr>
<td>
<select name="dropdown" id="dropdown">
<option> - </option>
<option id = "StudentA"> Student A </option>
<option id = "StudentB"> Student B </option>
</select>
</td>
<td></td>
<td></td>
</tr>
<tr>
<td>
<select name="dropdown" id="dropdown">
<option> - </option>
<option id = "StudentA"> Student A </option>
<option id = "StudentB"> Student B </option>
</select>
</td>
<td></td>
<td></td>
</tr>
</table>
JSON:
{"students":
[ {"studentName" : "studentA", "studentGrades" : "gradeC"}, {"studentName" : "studentB", "studentGrades" : "gradeA+"},
]
}
how to make when i select a drop down option of student A then student grades will automatically show on the table ?
i only did parse responsetext and did a console log and got it done i have all the students on the consolelog but not exactly sure how to do it with the select option dropdown.
Solution
You can try the below approach to achieve this. Add an onchange
event on the select tag and based on the selected option update the grades column.
Full working code:
const data = {
"students": [{
"studentName": "studentA",
"studentGrades": "gradeC"
}, {
"studentName": "studentB",
"studentGrades": "gradeA+"
}, ]
}
function showGrades() {
const dropdowns = document.querySelectorAll('#dropdown')
dropdowns.forEach(dropdown => {
const selectedVal = dropdown.options[dropdown.selectedIndex].id
const formattedVal = selectedVal.charAt(0).toLowerCase() + selectedVal.slice(1)
const grades = data.students.map(item => {
if (item.studentName == formattedVal) {
dropdown.parentElement.parentElement.children[1].innerText = item.studentGrades;
}
})
})
}
<table>
<tr>
<th>Student Name</th>
<th>Student Grades</th>
</tr>
<tr>
<td>
<select name="dropdown" id="dropdown" onchange="showGrades()">
<option> - </option>
<option id="StudentA"> Student A </option>
<option id="StudentB"> Student B </option>
</select>
</td>
<td></td>
</tr>
<tr>
<td>
<select name="dropdown" id="dropdown" onchange="showGrades()">
<option> - </option>
<option id="StudentA"> Student A </option>
<option id="StudentB"> Student B </option>
</select>
</td>
<td></td>
</tr>
</table>
Hope that's how you wanted it to work.
Answered By - Ankit Saxena
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.