繁体   English   中英

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

[英]Get custom attribute from selected option from datalist

当我从数据列表中选择一个选项时,我想获取其自定义属性“位置”并打印它。 我知道 select 有 selectedIndex 但我如何使用 datalist 完成此操作?

<!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>

 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>

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

我还发现,如果需要,一旦选择了值,datalist 将不可用,否则您可以查看该错误。

 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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM