【发布时间】:2012-12-06 07:28:20
【问题描述】:
如何使用 document.getElementById 获取两个值?
我有这段代码,我试图从选择框中获取 kontypeID 和 kontypeTitel 以写入文本字段:
<select id="select" name="select" onchange="run()">
<?php
$virksomhedsID = $_SESSION['virkID'];
$sql = "SELECT * FROM konkurrenceType ORDER BY konkurrenceType.kontypeID";
$result = mysql_query($sql) or die(mysql_error());
echo '<option value="Vælg type">Vælg type</option>';
while($rowSelect = mysql_fetch_assoc($result))
{
$kontypeID = $rowSelect['kontypeID'];
$kontypeTitel = $rowSelect['kontypeTitel'];
echo '<option value="' . $kontypeID . '">' . $kontypeTitel . '</option>';
}
?>
</select>
<script>
function run() {
var select = document.getElementById("select");
document.getElementById("valgtID").value = valgtTitel.options[select.selectedIndex].innerHTML;
document.getElementById("valgtTitel").value = valgtTitel.options[select.selectedIndex].innerHTML;
}
</script>
<input type="text" name="valgtID" id="valgtID"/>
<input type="text" name="valgtTitel" id="valgtTitel"/>
【问题讨论】:
-
你有两个相同
id的元素吗? -
没有。
document.getElementById只返回第一次出现。但是,如果你真的需要它们,你可以使用document.querySelectorAll("#id")。 -
不,我有 $kontypeID = $rowSelect['kontypeID']; $kontypeTitel = $rowSelect['kontypeTitel'];从我需要编写以分隔文本字段的选择框
-
document.querySelectorAll("#id") 长什么样子?
-
您是说您希望能够同时将 2 个不同文本区域的值设置为相同的文本?