JS JQuery Dynamic Add select option

  • 2021-06-28 10:04:29
  • OfStack

Today a friend asked me about < select > I added the option question dynamically in, 1 thought it was from JS at first, so I used JS to add option dynamically, but you used JQuery there, so I made a mistake. Here's the difference between adding option in JS and JQuery.

JS:


var selid = document.getElementById("sltid");
for(var i=0; i<10;i++){ // Loop to add multiple values 
sid.option[i] = new Option(i,i);
}
sid.options[sid.options.length]=new Option("1","2"); //  In the end 1 Add more after each value 1 individual 

JQuery:


$("#selectId").append("<option value='"+value+"'>"+text+"</option>");

Of course, in addition to this sentence, you also set the default selection value, the first value, the last value, the value of N, and so on, so you search 1 on the web:

jQuery gets Text and Value selected by Select:

1. $("#select_id "). change (function (){//code...}); //Add events for Select, triggered when one of them is selected

2. var checkText=$("#select_id (). find ("option:selected"). text (); //Get Text selected by Select

3. var checkValue=$("#select_id "). val();//Get Value selected by Select

4. var checkIndex=$("#select_id'). get (0). selectedIndex; //Get the index value selected by Select

5. var maxIndex=$("#select_id option: last'). attr ('index'); //Get maximum index value of Select

jQuery adds/deletes Option items for Select:

1. $("#select_id").append(" < option value='Value' > Text < /option > ";//Append an Option (drop-down item) to Select

2. $("#select_id").prepend(" < option value='0' > Please select < /option > ";//Insert an Option for Select (first position)

3. $("#select_id option: last "). remove(); //Delete maximum index value Option in Select (last one)

4. $("#select_id option [index='0'] ".remove();//Delete Option with index value 0 in Select (first)

5. $("#select_id option [value='3'] ".remove();//Delete Value='3'from Select

5. $("#select_id option [text='4'] ".remove();//Delete Option from Select with Text='4'


Related articles: