2 回答
TA贡献1828条经验 获得超6个赞
您可以创建一个函数,并在select 的onchange上调用该函数,将其作为参数传递。 this指向调用该函数的 html 元素。您可以尝试以下代码段。此外,我还对populateSelects进行了一些修改,以便能够在一次调用中创建所有下拉菜单。
// Step 1 - Store Strings to be passed to categoryOptions Parameter
let progressOptions = ["Just testing!", "XX has made excellent progress", "XX has made good progress", "XX has made poor progress"];
// Behaviour Options
let behaviourOptions = ["XX has excellent behaviour", "XX has good behaviour", "XX has poor behaviour"];
// Attendance Options
let attendanceOptions = ["XX has excellent attendance", "XX has good attendance", "XX has poor attendance"];
// Punctuality Options
let punctualityOptions = ["XX has excellent punctuality", "XX has good punctuality", "XX has poor punctuality"];
// Improvement Options
let improvementsOptions = ["XX should carry on as they have", "XX could make some improvements", "XX must improve"];
// Step 2 - Target the ID; objects to be used in the select below.
let dropDownConfig = [{
id: "progressDropdown",
categoryOptions: progressOptions
},
{
id: "behaviourDropdown",
categoryOptions: behaviourOptions
},
{
id: "attendanceDropdown",
categoryOptions: attendanceOptions
},
{
id: "punctualityDropdown",
categoryOptions: punctualityOptions
},
{
id: "improvementsDropdown",
categoryOptions: improvementsOptions
},
]
// Step 3 - For Loop Passing the Values from progressOptions as option elements in HTML
function populateSelects(dropDownConfig) {
for (let di = 0; di < dropDownConfig.length; di++) {
for (let i = 0; i < dropDownConfig[di].categoryOptions.length; i++) {
let opt = dropDownConfig[di].categoryOptions[i];
let el = document.createElement("option");
el.text = opt;
el.value = opt;
document.getElementById(dropDownConfig[di].id).add(el);
}
}
}
// Step 4 - Function which will print the selected value into the content HTML element
// Need helping turning this into a callback for the function above.
// I want this function to run but only when the select box is changed.
function printSelection(e) {
document.getElementById("content").innerHTML+= e.value+' ';
}
populateSelects(dropDownConfig);
<body>
<select id="progressDropdown" onchange="printSelection(this)">
<option>Progress Dropdown</option>
</select>
<select id="behaviourDropdown" onchange="printSelection(this)">
<option>Behaviour Dropdown</option>
</select>
<select id="attendanceDropdown" onchange="printSelection(this)">
<option>Attendance Dropdown</option>
</select>
<select id="punctualityDropdown" onchange="printSelection(this)">
<option>Punctuality Dropdown</option>
</select>
<select id="improvementsDropdown" onchange="printSelection(this)">
<option>Improvements Dropdown</option>
</select>
<div id="content"></div>
</body>
TA贡献1824条经验 获得超5个赞
您可以创建一个函数,您可以在其中传递下拉元素并提取其值。
function printSelected(element){ document.getElementById("content").innerHTML = element.value; }
并将您的 HTML 更改为:
<select id="progressDropdown" onchange="printSelected(this)"> <option>Progress Dropdown</option> </select>
您可以将此功能与所有其他下拉菜单一起使用。
添加回答
举报