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

来源:互联网 发布:抗美援朝有必要吗 知乎 编辑:程序博客网 时间:2024/04/30 13:35
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("");
0 0
原创粉丝点击