我想在html表单
的下拉
列表中添加一个选项。该选项将从文本框
中读取,然后将其添加到下拉
列表中。我是 javascript
新手。这是我的代码:
<html>
<head>
<script>
function addval()
{
alert ("script ee");
var x=document.getElementById("myselect");
var y=document.getElementById("mtxt");
x.Add(y);
alert ("inserted in dropdown");
}
</script>
</head>
<body>
<form>
<select id="myselect" name="select">
<option>op1</option>
<option>op2</option>
<option>op3</option>
<option>op4</option>
</select>
<input type="text" name="mytext" id="mtxt">
<input type="button" value="add" onClick="addval()">
</form>
</body>
</html>
最佳答案
没有Add
HTMLSelectElement中的方法类。
您必须创建元素<option>
手动:
function addval()
{
var x = document.getElementById("myselect");
var y = document.getElementById("mtxt");
var newOpt = document.createElement('option');
newOpt.textContent = y.value;
x.appendChild(newOpt);
}
<html>
<head>
<script>
function addval()
{
var x = document.getElementById("myselect");
var y = document.getElementById("mtxt");
var newOpt = document.createElement('option');
newOpt.textContent = y.value;
x.appendChild(newOpt);
}
</script>
</head>
<body>
<form>
<select id="myselect" name="select">
<option>op1</option>
<option>op2</option>
<option>op3</option>
<option>op4</option>
</select>
<input type="text" name="mytext" id="mtxt">
<input type="button" value="add" onClick="addval()">
</form>
</body>
</html>
关于javascript - 从文本框中读取文本并将其设置在 html #html #javascript 的下拉菜单中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32719951/