Home > Article > Web Front-end > jQuery dynamically adds and deletes select items (implementation code)
The following is a detailed analysis and introduction to the implementation code of jQuerydynamically adding deleting select items. Friends in need can come and refer to it
Copy code The code is as follows:
//Add
function col_add() {
var selObj = $("#mySelect");
var value="value ";
var text="text";
selObj.append("");
}
// Delete
function col_delete() {
var selOpt = $("#mySelect option:selected");
selOpt.remove();
}
// Clear
function col_clear() {
var selOpt = $("#mySelect option");
selOpt.remove();
}
The above methods are for jQuery to dynamically add, delete and clear selection. The following is how to write pure js:
Copy code The code is as follows:
var sid = document.getElementById(" mySelect");
sid.options[sid.options.length]=new Option("text","value"); // Add an item at the end of select
## Other commonly used methods:
Copy code The code is as follows:
$("#mySelect").change(function(){// code...}); //Triggered when the selected item changes
var text=$("#mySelect").find("option:selected").text (); //Get the Text
var value=$("#mySelect").val(); //Get the Value
var value=$("#mySelect option: selected").attr("value"); //Get the Value of the Select item
var index=$("#mySelect").get(0).selectedIndex; //Get the
of the Select item Index value, starting from 0 var index=$("#mySelect option:selected").attr("index"); //Not available! ! !
var index=$("#mySelect option:selected").index(); //Get the index value of the Select option, starting from 0
var maxIndex=$("#mySelect option:last") .attr("index"); //Not available! ! !
var maxIndex=$("#mySelect option:last").index();//Get the Select maximum index value, starting from 0
$("#mySelect").prepend(""); //Insert an item before the first item in Select
//Set the selected item according to the index
$( "#mySelect").get(0).selectedIndex=index;//index is the index value
//Set the selected item according to value
$("#mySelect").attr("value","newValue ");
$("#mySelect").val("newValue");
$("#mySelect").get(0).value = value;
//According to text settings The item is the selected item
var count=$("#mySelect option").length;
for(var i=0;i
if($(" #mySelect").get(0).options[i].text == text)
{
$("#mySelect").get(0).options[i].selected = true;
break;
}
$("#mySelect").empty();
The above is the detailed content of jQuery dynamically adds and deletes select items (implementation code). For more information, please follow other related articles on the PHP Chinese website!