Home > Web Front-end > JS Tutorial > body text

jQuery dynamically adds and deletes select items

巴扎黑
Release: 2017-06-29 10:11:40
Original
1000 people have browsed it

// 添加
function col_add() {
	var selObj = $("#mySelect");
	var value="value";
	var text="text";
	selObj.append("<option value=&#39;"+value+"&#39;>"+text+"</option>");
}
// 删除
function col_delete() {
	var selOpt = $("#mySelect option:selected");
	selOpt.remove();
}
// 清空
function col_clear() {
	var selOpt = $("#mySelect option");
	selOpt.remove();
}
Copy after login

The above method isjQuerydynamically add, delete and clear the select. The following is how to write pure js:

var sid = document.getElementById("mySelect");
       
sid.options[sid.options.length]=new Option("text","value");   // 在select最后添加一项
Copy after login

Other commonly used methods:

$("#mySelect").change(function(){//code...});    //select选中项改变时触发

// 获取select值
var text=$("#mySelect").find("option:selected").text();   //获取Select选中项的Text
var value=$("#mySelect").val();   //获取Select选中项的Value
var value=$("#mySelect option:selected").attr("value");   //获取Select选中项的Value
var index=$("#mySelect").get(0).selectedIndex;   //获取Select选中项的索引值,从0开始
var index=$("#mySelect option:selected").attr("index");   //不可用!!!
var index=$("#mySelect option:selected").index();   //获取Select选中项的索引值,从0开始
var maxIndex=$("#mySelect option:last").attr("index");   //不可用!!!
var maxIndex=$("#mySelect option:last").index();//获取Select最大索引值,从0开始
$("#mySelect").prepend("<option value=&#39;value&#39;>text</option>");   //Select第一项前插入一项

// 设置select值
//根据索引设置选中项
$("#mySelect").get(0).selectedIndex=index;//index为索引值 
//根据value设置选中项
$("#mySelect").attr("value","newValue"); 
$("#mySelect").val("newValue"); 
$("#mySelect").get(0).value = value; 
//根据text设置对应的项为选中项
var count=$("#mySelect option").length; 
for(var i=0;i<count;i++) 
{ 
    if($("#mySelect").get(0).options[i].text == text) 
    { 
        $("#mySelect").get(0).options[i].selected = true; 
        break; 
    } 
} 

// 清空select
$("#mySelect").empty();
Copy after login

The above is the detailed content of jQuery dynamically adds and deletes select items. For more information, please follow other related articles on the PHP Chinese website!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!