Home  >  Article  >  Web Front-end  >  How to dynamically add option to select using js (detailed tutorial)

How to dynamically add option to select using js (detailed tutorial)

亚连
亚连Original
2018-06-09 14:37:4111096browse

Below I will share with you a method of using js to dynamically add options to datalist or select. It has a good reference value and I hope it will be helpful to everyone.

Sometimes it is necessary to read information from the configuration file and then add it to the user's options, such as the option option of select. Here is an example for such a situation

The content is as follows:

<!DOCTYPE html>
<html>
<head>
<title>鼠标点击时加载</title>
<script type="text/javascript" src="jquery-1.8.3.js"></script>
</head>
<body>
选择城市:<input type="text" name="cname" list="cities"/><br/>
<datalist id="cities">
</datalist>
</body>
</html>
<script type="text/javascript">
//需要添加的数据内容,可以通过ajax请求获取
var cities = [
{label:"xian",value:"西安"},
{label:"hubei",value:"湖北"},
{label:"wuhai",value:"武汉"}
]; 
//获取datalist的dom
var ss = document.getElementById("cities");
//定义加载城市的函数
function loadcities(){
for(var i = 0;i < cities.length; i ++){
var city = cities[i];
//纯js实现的方式
/*var op=document.createElement("option"); 
op.setAttribute("label",city.label);
op.setAttribute("value",city.value); 
ss.appendChild(op);*/ 
//jquery实现的方式
$("#cities").append(&#39;<option label="&#39;+city.label+&#39;" value="&#39;+city.value+&#39;"></option>&#39;);
}
}
//页面加载完时加载此函数
window.onload = function(){
loadcities();
}
</script>

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

AngularJS two-way data binding principle (detailed tutorial)

Related data storage and value acquisition in WeChat applet Question

How to implement the streamlined style in Vue (detailed tutorial)

How to customize the global component in vue?

How to implement multi-page development in vue2.0

How to implement the drag verification code function using jQuery and vue

The above is the detailed content of How to dynamically add option to select using js (detailed tutorial). For more information, please follow other related articles on the PHP Chinese website!

Statement:
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