从数据列表中选择州名(即加利福尼亚州)后,我想在结果中显示option id=
中的州缩写
如何在options
中定义和访问datalist
?
例如,如果从California
中选择了datalist
,我想返回结果CA
。
var input = document.getElementById("myInputId");
input.addEventListener("keyup", function(event) {
event.preventDefault();
if (event.keyCode === 13) {
document.getElementById("myButton").click();
}
});
function result() {
document.getElementById("myResult").innerHTML = input.value;
myObj.info.forEach(function(e, z) {
var q = document.getElementById("myResult").innerHTML;
if (e.properties.id == q) {
document.getElementById("position").innerHTML = z;
document.getElementById("width").innerHTML = myObj.info[z].properties.width;
}
});
}
myObj = {
"type":"A",
"info": [
{ "item":"1", "properties":{ "id":"Alabama", "height": "25", width: "50" } },
{ "item":"2", "properties":{ "id":"California", "height": "30", width: "40" } },
{ "item":"3", "properties":{ "id":"Vermont", "height": "20", width: "100" } }
]
}
<input list="myInput" id="myInputId" value="" option="">
<button id="myButton" onClick="result()">submit</button>
<datalist id="myInput">
<option id="AL">Alabama</option>
<option id="CA">California</option>
<option id="VT">Vermont</option>
</datalist>
<p>Option ID (State abbreviation):<span id="option"></span></p>
<p>Result:<span id="myResult"></span></p>
<p>Position in object:<span id="position"></span></p>
<p>Width:<span id="width"></span></p>
答案 0 :(得分:2)
使用this.getAttribute('id')
从输入字段中获取ID。
然后如下所示:
document.getElementById('myInput').getElementsByTagName('option')[z].getAttribute('id')
var input = document.getElementById("myInputId");
input.addEventListener("keyup", function(event) {
event.preventDefault();
if (event.keyCode === 13) {
document.getElementById("myButton").click();
}
});
function result() {
document.getElementById("myResult").innerHTML = input.value;
myObj.info.forEach(function(e, z) {
var q = document.getElementById("myResult").innerHTML;
if (e.properties.id == q) {
document.getElementById("position").innerHTML = z;
document.getElementById("width").innerHTML = myObj.info[z].properties.width;
document.getElementById("option").innerHTML = document.getElementById('myInput').getElementsByTagName('option')[z].getAttribute('id');
}
});
}
myObj = {
"type":"A",
"info": [
{ "item":"1", "properties":{ "id":"Alabama", "height": "25", width: "50" } },
{ "item":"2", "properties":{ "id":"California", "height": "30", width: "40" } },
{ "item":"3", "properties":{ "id":"Vermont", "height": "20", width: "100" } }
]
}
<input list="myInput" id="myInputId" value="" option="">
<button id="myButton" onClick="result()">submit</button>
<datalist id="myInput">
<option id="AL">Alabama</option>
<option id="CA">California</option>
<option id="VT">Vermont</option>
</datalist>
<p>Option ID (State abbreviation):<span id="option"></span></p>
<p>Result:<span id="myResult"></span></p>
<p>Position in object:<span id="position"></span></p>
<p>Width:<span id="width"></span></p>