select下拉框的选择和赋值

版权声明:本文为博主原创文章,如若转载,请注明文章出处。 https://blog.csdn.net/qq_34129814/article/details/80166256

1、获取选中的select的option的值value和文本text

var checkValue = $("#select_id").val();   ***** 获取Select选中项的Value

var checkValue = $(‘#select_id option:selected’).val(); * 获取Select选中项的Value

var checkText = $("#select_id :selected").text();    ***** 获得选中的select的文本

var checkTextw =  $("#select_id").find("option:selected").val();    ***** 获得选中的select的文本

1.1 获取相应option的值

var checkValue = $(‘#select_id option:first’).val();*获取第一个option的值

var checkValue =$(“#select_id option:last”).val();*最后一个option的值

var checkValue = $(‘#select_id option:eq(1)’).val();**获取第二个option的值

2.设置相应的option被选中

$(“#select_id”).val(“BMW*”); 设置Select的Value值为BMW的项选中

$(“#select_id”).get(0).value = “BMW*”; *选中value值为BMW*

$(“#select_id”).get(0).selectedIndex = 1; *设置Select索引值为1的项选中

$(“#select_id”).find(“option[value=’BMW*’]”).attr(“selected”,true); *设置value为BMW的项选中

但是:$(“#select_id option[text=’Audi’]”).attr(“selected”,true); 不管用

3.获取相应的option的索引

var maxIndex = $(“#select_id :last”).get(0).index; **/获取select最大索引值

var checkIndex = $(“#select_id”).get(0).selectedIndex;**获取Select选中项的索引值

var checkIndexs = $(‘option:selected’, ‘#select_id’).index(); **获取选中的select的索引

var checkIndexa = ('#select_id option').index( (‘#select_id option:selected’)) *获取选中的select的索引

var checkIndex = $(‘#select_id’).prop(‘selectedIndex’); **获取选中的select的索引

@<%–var checkIndex =$(‘#select_id optgroup:eq(1):option:eq(0)’).val(); //获取第二group下面第一个option的值 不知管不管用 没有测–%>

4.判断是否被选中

alert($(“#select_id”).find(“option[value=’BMW*’]”).is(“:selected”)); *选中为true 没选中为false

alert(document.getElementById(“select_id”).options[1].selected); **判断选中为true 没选中为false

5.追加和移除option

$(“#select_id”).append(“新增option“); **为Select追加一个Option(下拉项)

$(“#select_id”).prepend(“请选择“); *为Select插入一个Option(第一个位置)

$(“#select_id”).get(0).remove(1); * 删除Select中索引值为1的Option(第二个)

$(“#select_id [value=’BMW*’]”).remove(); *删除Select中Value=’3’的Option

6.根据文本进行选择:

var street = ‘BMW’;

$(‘#select_id option:contains(’ + street + ‘)’).each(function(){

  if ($(this).text() == street) {

     $(this).attr('selected', true);

  }

});

**文本为BMW的option被选中 contains和index of()的作用一样

var numId=”BMW” *设置text==BMW的选中!

var count=$(“#select_id option”).length;

for(var i=0;i

猜你喜欢

转载自blog.csdn.net/qq_34129814/article/details/80166256
今日推荐