Home > Article > Web Front-end > Detailed explanation of dynamically adding options to datalist or select using js
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('<option label="'+city.label+'" value="'+city.value+'"></option>'); } } //页面加载完时加载此函数 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!