通过JavaScript操作HTML中select标签

267 篇文章 1 订阅
107 篇文章 2 订阅

添加:

Js代码
1.function selectChange()   
2.{   
3. var sel=document.getElementById("select1");   
4. Option option = new Option("Text","Value");   
5. sel.add(option);   
6.}   
function selectChange()
{
  var sel=document.getElementById("select1");
  Option option = new Option("Text","Value");
  sel.add(option);
}  

删除所有:

Js代码
1.document.getElementById("select1").options.length=0;   
  document.getElementById("select1").options.length=0;删除单个Option元素:

Js代码
1.var sel=document.getElementById("select1");   
2.for(i=0;i<sel.options.length;i++)   
3.{   
4. if(sel.options[i].selected)   
5. {   
6. sel.options[i]=null; //设置为null就删除了这个元素   
7. }   
8.}   
var sel=document.getElementById("select1");
for(i=0;i<sel.options.length;i++)   
{   
  if(sel.options[i].selected)   
  {   
  sel.options[i]=null; //设置为null就删除了这个元素
  }   
} 取值:

Js代码
1.var sel=document.getElementById("select1"):   
2.var val=sel.options[sel.selectedIndex].value   //亦可以这样写  var val = sel.value;
3.alert(val); //得到Option的value   
4.var txt=sel.options[sel.selectedIndex].text   
5.alert(txt); //得到Option的文本(即Text)  

如果你对编程感兴趣或者想往编程方向发展,可以关注微信公众号【筑梦编程】,大家一起交流讨论!小编也会每天定时更新既有趣又有用的编程知识!
 

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用JavaScript来将一个input元素转换为select元素。以下是一个示例代码: ```html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Convert input to select</title> </head> <body> <label for="myInput">请选择一个选项:</label> <input type="text" id="myInput" name="myInput" value="选项1"> <button onclick="convertInputToSelect()">转换为下拉列表</button> <script> function convertInputToSelect() { // 获取 input 元素 var input = document.getElementById("myInput"); // 创建 select 元素 var select = document.createElement("select"); select.setAttribute("name", input.getAttribute("name")); select.setAttribute("id", input.getAttribute("id")); // 创建选项元素 var option1 = document.createElement("option"); option1.setAttribute("value", "选项1"); option1.textContent = "选项1"; var option2 = document.createElement("option"); option2.setAttribute("value", "选项2"); option2.textContent = "选项2"; var option3 = document.createElement("option"); option3.setAttribute("value", "选项3"); option3.textContent = "选项3"; // 添加选项元素到 select 元素 select.appendChild(option1); select.appendChild(option2); select.appendChild(option3); // 替换 input 元素为 select 元素 input.parentNode.replaceChild(select, input); } </script> </body> </html> ``` 在上面的示例,我们首先创建一个input元素和一个按钮,然后在点击按钮时调用convertInputToSelect函数。在函数,我们首先获取input元素,然后创建一个select元素,并根据input元素的属性设置select元素的name和id属性。接着,我们创建了三个option元素,并将它们添加到select元素。最后,我们使用parentNode.replaceChild()方法将input元素替换为select元素。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值