Home  >  Article  >  Web Front-end  >  How to use the select component in jquery

How to use the select component in jquery

php中世界最好的语言
php中世界最好的语言Original
2018-03-14 15:36:041945browse

This time I will bring you how to use the select component in jquery, and what are the precautions for using the select component in jquery. The following is a practical case, let's take a look.

jquery gets the text and value selected by select

Get select:

Get the selected text of select:

$(“#ddlregtype”).find(“option:selected”).text();

Get the selected value of select:

$(“#ddlregtype “).val();

Get the selected index of select:

$(“#ddlregtype “).get(0).selectedindex;

Set select :

Set select selected index:

$(“#ddlregtype “).get(0).selectedindex=index;//index为索引值

Set select selected value:

(“#ddlregtype “).attr(“value”,”normal“);(“#ddlregtype “).attr(“value”,”normal“);(“#ddlregtype “).val(“normal”); 
$(“#ddlregtype “).get(0).value = value;

Set select selected text :

var count=$("#ddlregtype option").length;
 for(var i=0;i<count;i++)
   {      if($("#ddlregtype ").get(0).options[i].text == text)
    {
      $("#ddlregtype ").get(0).options[i].selected = true;
      break;
    }
  }
$("#select_id option[text=&#39;jquery&#39;]").attr("selected", true);

Set the select option item:

$("#select_id").append("<option value=&#39;value&#39;>text</option>"); //添加一项option
$("#select_id").prepend("<option value=&#39;0&#39;>请选择</option>"); //在前面插入一项option
$("#select_id option:last").remove(); //删除索引值最大的option
$("#select_id option[index='0']").remove();//删除索引值为0的option
$("#select_id option[value='3']").remove(); //删除值为3的option
$("#select_id option[text='4']").remove(); //删除text值为4的option

Clear the select:

$("#ddlregtype ").empty();

Work needs to get the values ​​​​in the two forms. As shown in the picture:

How to get the value added from the left selection box to the right selection box? I thought about using web page special effects to get it, and the more popular jquery was used here.

js code is as follows:

//获取所有属性值 var item = $("#select1").val();
$(function(){
 $('#select1').each( //获得select1的所有值
   function(){
    $('button').click(function(){
      alert($('#select2').val()); //获得select2中的select1值
    });
   });
})
</script>

It is worth noting that it cannot be written directly as

$(function(){
 $('#select2').each( //获得select1的所有值,因为前面讲选项从左边添加到右边,jquery其实并没有真正将值从左边传到右边。
   function(){
    $('button').click(function(){
      alert($(this).val()); //获得select2中的select1值
    });
   });
})

html:

Option 1
Option 2
Option 3
Option 4
Option 5
Option 6
Option 7

Select to add to the right>>
Add all to the right>>

<