select基本的取值,赋值及清空

1.获取select被选中的option的值
js实现
var selected = document.getElementById('selectedId'); //定位id
var index = selected.selectedIndex; // 选中索引
var text = selected.options[index].text; // 选中文本
var value = selected.options[index].value; // 选中值


jQuery实现
第一种方式
$('#selectId option:selected').text();//选中的文本
$('#selectId option:selected') .val();//选中的值
$("#selectId ").get(0).selectedIndex;//索引


第二种方式
$("#selectId").find("option:selected").text();//选中的文本
$("#selectId").find("option:selected").val();//选中的值
$("#selectId").find("option:selected").get(0).selectedIndex;//索引


2.给select动态添加值
第一种方法
 var select = document.getElementById("selectId");
 var item = new Option(text,val);
 select .add(item);
第二种方法
var item =$('<select></select>');  
for(var i=0;i<5;i++){  
  item.append('<option value="'+i+'">'+i+'</option>');  
}


3.将select的值清空
js实现
方法一
document.getElementById("selectId").options.length = 0; 


方法二
document.formName.selectName.options.length = 0;


方法三
document.getElementById("selectId").innerHTML = "";


jQuery实现
方法一
$("#selectId").find("option").remove(); 
方法二
$("#selectId").empty();
方法三
$("#selectId").html("");
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值