[英]how can I get attributes of selected option of datalist on input tag
I have the following html我有以下 html
Area: <input onchange="loadInfo()" id="area_input" list="areas" placeholder="choose option: ">
<datalist id="areas" >
<option abrv="TV"> TV </option>
<option abrv="NOT"> NOTEBOOK </option>
<option abrv="ARC"> AIR CONDITIONING </option>
<option abrv="PIN"> PINS </option>
</datalist>
I learned that when the user selects an option, I can get its value via Javascript doing我了解到,当用户选择一个选项时,我可以通过 Javascript 获得它的价值
document.getElementById('area_input').value
My objective is to get the 'abrv' attribute, however I noticed it does not get carried to input tag.我的目标是获取“abrv”属性,但我注意到它没有被传送到输入标签。
How can I get attributes from the selected option via JS?如何通过 JS 从选定的选项中获取属性?
PS (my intention is to use it to append to a DJANGO url 'database/area/[abrv]' and even if on this specific case I can do some work-around striping the value string, on the future I will need to get codes from strings) PS(我的目的是将它用于 append 到 DJANGO url 'database/area/[abrv]' 并且即使在这种特定情况下我可以做一些解决方法来条带化值字符串,在未来我需要得到来自字符串的代码)
I tried this solution:我试过这个解决方案:
FROM Get Id of selected item in datalist
FROM 获取数据列表中所选项目的 Id
it ended up showing things in a weird way它最终以一种奇怪的方式展示了东西
the resulting code was like this
结果代码是这样的
`<datalist id="areas">
<option value="IMC">IMC</option>
<option value="INJ">INJEÇÃO PLÁSTICA</option>
<option value="NOT">NOTEBOOK</option>
<option value="TRA">TRANSFORMADOR</option>
<option value="TV">TV</option>
</datalist>`
the solution told me user would see only what was inside the tag, but on cases where the attribute value was different than the actual value inside the tag it showed the user both info, I wanted to show only the full text to the user该解决方案告诉我用户只会看到标签内的内容,但在属性值与标签内的实际值不同的情况下,它会向用户显示这两种信息,我只想向用户显示全文
You can store extra information in data-* attributes.您可以在 data-* 属性中存储额外信息。 Then search options list for match by input's value:
然后通过输入的值搜索选项列表以匹配:
HTML HTML
<input onchange="loadInfo()" id="iareas" list="areas" placeholder="choose option: ">
<datalist id="areas" >
<option data-value="TV">TV</option>
<option data-value="NOT">NOTEBOOK</option>
<option data-value="ARC">AIR CONDITIONING</option>
<option data-value="PIN">PINS</option>
</datalist>
SCRIPT脚本
function loadInfo() {
const data = document.getElementById("areas");
const opts = data.options;
const v = document.getElementById("iareas").value;
for(let i=0; i<opts.length; i++) {
const o = opts[i];
if(o.text === v) {
console.log(o.getAttribute("data-value")); //do anything with value
break;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.