Home  >  Article  >  Web Front-end  >  Detailed explanation of dynamically adding options to datalist or select using js

Detailed explanation of dynamically adding options to datalist or select using js

小云云
小云云Original
2018-05-19 14:01:402910browse

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. This article mainly shares a method of using js to dynamically add options to datalist or select, which has many advantages. Good reference value, I hope it will be helpful to everyone. Let’s follow the editor to take a look, I hope it can help everyone.

The following is an example for this kind of 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>

Related recommendations:

How to dynamically add option to control select_html/css_WEB-ITnose

jquery dynamically add option example_jquery

js method of adding options to selected_javascript skills

The above is the detailed content of Detailed explanation of dynamically adding options to datalist or select using js. 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