Today a friend asked me a question about dynamically adding options in
JS:
var selid = document.getElementById("sltid"); for(var i=0; i<10;i++){ //循环添加多个值 sid.option[i] = new Option(i,i); } sid.options[sid.options.length]=new Option("1","2"); // 在最后一个值后面添加多一个
JQuery:
$("#selectId").append("<option value='"+value+"'>"+text+"</option>");
Of course, in addition to this sentence, there are also ways to set the default selection value, the first value, the last value, the Nth value, etc., so I searched on the Internet:
jQuery gets the Text and Value selected by Select:
1. $("#select_id").change(function(){//code...}); //Add events for Select, Triggered when one of the items is selected
2. var checkText=$("#select_id").find("option:selected").text(); //Get the Text selected by Select
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 to add/delete the Option item of Select:
1. $("#select_id").append("< ;option value='Value'>Text"); //Add an Option (drop-down item) to Select
2. $("#select_id").prepend(" "); //Insert an Option (first position) for Select
3. $("#select_id option :last").remove(); //Delete the Option with the largest index value in Select (the last one)
4. $("#select_id option[index='0']").remove (); //Delete the Option (first one) with index value 0 in Select
5. $("#select_id option[value='3']").remove(); //Delete the Option with Value='3' in Select
5. $("#select_id option[text='4']").remove(); //Delete the Text= in Select '4''s Option
The above is the knowledge about dynamically adding select options in JS & JQuery introduced by the editor. I hope it will be helpful to you. If you have any questions, please let me know. Leave a message and the editor will reply to you in time. I would also like to thank you all for your support of the PHP Chinese website!
For more JS & JQuery dynamically adding select option related articles, please pay attention to the PHP Chinese website!