从数据列表中的选定选项获取自定义属性



当我从数据列表中选择一个选项时,我想获得它的自定义属性"位置";并打印它。我知道select已经选择了Index,但我如何使用数据列表来实现这一点?

<!DOCTYPE html>
<html>
<body>
<input type="text" id="StartingAddressField" size="50" placeholder="Select item from list" list="select">
<datalist id="select" style="display:none;" onchange="Select1Changed();">
<option value="one" location="3"/>
<option value="two" location="15"/>
<option value="three" location="27"/>
</datalist>
</body>
</html>

通过使用document.getElementById选择元素,您将获得HTMLCollection,您可以对其进行迭代(在本例中为选项列表(,并使用附加到每个元素的属性对象找到所需的属性。

此外,我发现一旦选择了值,数据列表就不可用了。如果需要,那么好吧,否则你可能会调查这个错误。

function Select1Changed(elem) {
let location = 'please select a valid option';
let dt = document.getElementById('select');
// dt contains a HTMLCollection of options so use for loop to iterate it use childElementCount to get the length if loop
for (let i = 0; i < dt.childElementCount; i++) {
// check the selected value with option values.
if (dt.children[i].attributes.value.value === elem.value) {
// if Hit use the attributes object to find your attribute and get its value.
location = dt.children[i].attributes.location.value;
}
}
alert(location);
}
<!DOCTYPE html>
<html>
<body>
<input type="text" id="StartingAddressField" size="50" placeholder="Select item from list" list="select" onchange="Select1Changed(this);">
<datalist id="select" style="display:none;">
<option value="one" location="3"/>
<option value="two" location="15"/>
<option value="three" location="27"/>
</datalist>
</body>
</html>

const dataList = document.getElementById('select');
const textInput = document.getElementById('StartingAddressField');
const getSelecteOptionLocation = () => {
for (let i = 0; i < dataList.options.length; i++) {
if (dataList.options[i].value === textInput.value) {
return dataList.options[i];
}
}
}
textInput.addEventListener('change', () => {
const selectedOption = getSelecteOptionLocation();
if (selectedOption == undefined) {
console.log('option not included in the datalist');
} else {
console.log(selectedOption.getAttribute('location'));
}
});
<!DOCTYPE html>
<html>
<body>
<input type="text" id="StartingAddressField" size="50" placeholder="Select item from list" list="select" onBlur="getSelecteOptionLocation()">
<datalist id="select" style="display:none;">
<option value="one" location="3" />
<option value="two" location="15" />
<option value="three" location="27" />
</datalist>
</body>
</html>

最新更新