Home > Web Front-end > JS Tutorial > jQuery dynamically adds and deletes select items (implementation code)_jquery

jQuery dynamically adds and deletes select items (implementation code)_jquery

WBOY
Release: 2016-05-16 17:23:49
Original
1093 people have browsed 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

//Get the select value
var text=$("#mySelect").find("option:selected").text(); //Get the Text of the Select item
var value=$ ("#mySelect").val(); //Get the Value of the Select item
var value=$("#mySelect option:selected").attr("value"); //Get the Value of the Select item Value
var index=$("#mySelect").get(0).selectedIndex; //Get the index value of the Select option, 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 select value
//Set the selected item according to the index
$("#mySelect").get(0).selectedIndex=index;//index is the index value
//According to value sets the selected item
$("#mySelect").attr("value","newValue");
$("#mySelect").val("newValue");
$(" #mySelect").get(0).value = value;
//Set the corresponding item as the selected item according to the text
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;
}
}

// Clear selection
$("#mySelect").empty();

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template