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.
uj5u.com熱心網友回復:
您可以嘗試以下方法來實作此目的。在選擇標簽上添加一個onchange事件,并根據所選選項更新成績列。
完整的作業代碼:
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>
希望這就是您希望它作業的方式。
uj5u.com熱心網友回復:
您可以通過onchange在 select 上觸發事件然后使用Array.filter()方法過濾出學生陣列來獲得選定的選項來實作它studentGrade。
作業演示:
const obj = {
"students": [
{"studentName" : "studentA", "studentGrades" : "gradeC"},
{"studentName" : "studentB", "studentGrades" : "gradeA "},
]
};
function getGrades() {
const selectedOption = document.getElementById('dropdown').value;
document.getElementById('studentGrade').innerHTML = obj.students.find((obj) => obj.studentName === selectedOption).studentGrades;
}
<table>
<tr>
<th>Student Name</th>
<th>Student Grades</th>
</tr>
<tr>
<td>
<select name="dropdown" id="dropdown" onchange="getGrades()">
<option> - </option>
<option value="studentA"> Student A </option>
<option value="studentB"> Student B </option>
</select>
</td>
<td id="studentGrade"></td>
</tr>
</table>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/448565.html
標籤:javascript html json ajax
