我想在下拉菜单中进行选择,显示文字与实际值不同。一旦我做出选择,我希望SELECT框中显示的实际HTML显示实际值,而不是所选文本。
到目前为止,我有这个。它几乎可以工作,但是一旦我做出选择,它就会将可查看字段设置为值,但如果我再次单击下拉列表,则初始可选择的选项不再存在,只有值。
<select size="1" style="width: 28mm; border: 1px solid;"" name="Priority"
id="Priority" onChange="setDevices(this);">
<option selected><? print($row[Priority]); ?></option>
<option value="Pri1">This is Priority 1</option>
<option value="Pri2">This is Priority 2</option>
<option value="Pri3">This is Priority 3</option>
<option value="Pri4">This is Priority 4</option>
</select>
function setDevices(elem) {
elem.options[elem.selectedIndex].innerHTML = elem.options[elem.selectedIndex].value
}
答案 0 :(得分:1)
现在将其推迟到2019年,我们现在可以使用data attributes存储以前的信息
function setDevices(elem) {
let arrMeta = elem.dataset.meta.split("|");
let index = parseInt(arrMeta[0], 10);
let text = arrMeta[1];
//Reset the old text
elem.options[index].innerHTML = text;
//Set the meta from the new
elem.dataset.meta = elem.selectedIndex + "|" + elem.options[elem.selectedIndex].innerHTML;
//Update the new
elem.options[elem.selectedIndex].innerHTML = elem.value;
}
<select size="1" style="width: 28mm; border: 1px solid;" name="Priority" id="Priority" onchange="setDevices(this);" data-meta="0|">
<option selected>
<? print($row[Priority]); ?>
</option>
<option value="Pri1">This is Priority 1</option>
<option value="Pri2">This is Priority 2</option>
<option value="Pri3">This is Priority 3</option>
<option value="Pri4">This is Priority 4</option>
</select>
您当然可以使用2个数据属性,一个用于先前选择的索引,一个用于先前的文本。
答案 1 :(得分:0)
已编辑02/02/14
所以你想要“这是优先级1”,在选择时更改为“Pri1”,并在取消选择时更改回来?
第一次更改时,您需要将原始值存储在某处,并在选择更改时添加一些代码以恢复该存储的值。
您可以使用“rel”属性:
<select size="1" style="width: 28mm; border: 1px solid;"" name="Priority" id="Priority" onchange="setDevices(this);">
<option selected><? print($row[Priority]); ?></option>
<option value="Pri1" rel="This is Priority 1">This is Priority 1</option>
<option value="Pri2" rel="This is Priority 2">This is Priority 2</option>
<option value="Pri3" rel="This is Priority 3">This is Priority 3</option>
<option value="Pri4" rel="This is Priority 4">This is Priority 4</option>
</select>
<script>
function setDevices(elem){
for(i=0; i<elem.options.length; i++) {
elem.options[i].innerHTML = (i == elem.selectedIndex) ? elem.options[i].value : elem.options[i].getAttribute("rel");
}
}
</script>