SoFunction
Updated on 2025-02-28

JS & JQuery dynamically add select option

Today a friend asked me a question about adding options dynamically in <select>. At first I thought it was dynamically added in JS, so I used the method of adding options dynamically in JS, but you used JQuery, so there were always errors.Let's note the difference between adding option in JS and JQuery

JS:

var selid = ("sltid");
for(var i=0; i&lt;10;i++){ //Loop to add multiple values[i] = new Option(i,i);
}
[]=new Option("1","2"); // Add one more after the last value

JQuery:

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

Of course, in addition to this sentence, there are also settings for default selection values, first value, last value, Nth value, etc., so I searched online:

jQuery gets the Select Select Text and Value:

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

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

3. var checkValue=$("#select_id").val(); //Get the 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 the maximum index value of Select

jQuery adds/deletes Select's Option item:

1. $("#select_id").append("<option value='Value'>Text</option>"); //Add 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 the maximum index value Option in Select (last)

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

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

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

The above is the relevant knowledge about adding select option to JS & JQuery dynamically. I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to everyone in time. Thank you very much for your support for my website!