我选择了选项:
<form>
<select name="sel" id="sel" onchange="run()">
<option selected disabled>Wybierz...</option>
<optgroup id="user" value="user" label="user">
<option value="1">michal</option>
<option value="2">mateusz</option>
</optgroup>
<optgroup id="warehouse" value="warehouse" label="warehouse">
<option value="1">kosz</option>
<option value="2">zaginione</option>
</optgroup>
</select>
</form>
<input type="text" name="copy" id="copy"></input>
在输入文本中添加文本的脚本:
function run() {
if(document.getElementById("user").label == 'user'){
document.getElementById("copy").value = "user";
} else if (document.getElementById("warehouse").label == 'warehouse') {
document.getElementById("copy").value = "warehouse";
}
}
当用户首先使用optgroup
(“user”)选择选项时,然后在输入文本脚本中添加名称“user”。当用户从第二个optgroup
中选择记录时,脚本将输入文本中的文本更改为“warehouse”。但在我的脚本中,输入文本中没有添加任何内容。
demo
最佳答案
在 jsfiddle 中,您已将函数放入 onload 函数中,因此它未定义到外部范围。outherwise 您将获得两个组的 user
document.getElementById("user").label == 'user'
始终为 true。因此不会出现 else block 。您应该获取所选组的标签值并进行比较。
var lable=event.target.options[event.target.selectedIndex].parentNode.label // get lable value of clicked group
if(lable == 'user'){
document.getElementById("copy").value = "user";
} else if (lable == 'warehouse') {
document.getElementById("copy").value = "warehouse";
}
关于JavaScript 将值 optgroup 复制到其他输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38553470/