Jquery dropdown select control operation method share of jquery operation select

  • 2020-03-30 02:26:59
  • OfStack

The methods to get and set Select options in JQuery are summarized as follows:

Code:


$("#select_id").change(function(){//code...});   // for Select Adds an event that fires when one of the items is selected 
var checkText=$("#select_id").find("option:selected").text();  //Gets the Text of the Select selection
var checkValue=$("#select_id").val();  //Gets the Value of the Select
var checkIndex=$("#select_id ").get(0).selectedIndex;  //Gets the index value of the Select selection
var maxIndex=$("#select_id option:last").attr("index");  //Gets the largest index value of the Select
$("#select_id ").get(0).selectedIndex=1;  //Set the selection of an item with a Select index value of 1
$("#select_id ").val(4);   //Set the selection of an item with a Value of 4 in the Select
$("#select_id option[text='jQuery']").attr("selected", true);   //Set the Text value of Select to be selected by jQuery

Get the text selected by select:


$("#ddlRegType").find("option:selected").text();

Get the value selected by the select:


$("#nowamagic").val();

Gets the index selected by select:


$("#nowamagic").get(0).selectedIndex;

Set up the select

JQuery add/remove options of Select:


$("#select_id").append("<option value='Value'>Text</option>");  //Append an Option to the Select
$("#select_id").prepend("<option value='0'> Please select a </option>");  //Insert an Option(first position) for the Select
$("#select_id option:last").remove();  //Delete the largest Option with the index value in the Select (the last one)
$("#select_id option[index='0']").remove();  //Delete Option with index value of 0 in Select (first)
$("#select_id option[value='3']").remove();  //Delete the Option with Value='3' in Select
$("#select_id option[text='4']").remove();  //Delete the Option that Text='4' in Select

Set the index selected by select:


//Index is the index value
$("#nowamagic").get(0).selectedIndex=index;

Set the selected value of select:


$("#nowamagic").attr("value","Normal");
$("#nowamagic").val("Normal");
$("#nowamagic").get(0).value = value;

Set the text selected by select:


var count=$("#nowamagicoption").length;
  for(var i=0;i<count;i++)  
     {           if($("#nowamagic").get(0).options[i].text == text)  
        {  
            $("#nowamagic").get(0).options[i].selected = true;  

            break;  
        }  
    } 

To empty the select:


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


Related articles: