SoFunction
Updated on 2025-02-28

Methods to dynamically add option options to datalist or select using js

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

The content is as follows:

<!DOCTYPE html>
<html>
<head>
<title>Load when the mouse clicks</title>
<script type="text/javascript" src="jquery-1.8."></script>
</head>
<body>
Choose a city:<input type="text" name="cname" list="cities"/><br/>
<datalist >
</datalist>
</body>
</html>
<script type="text/javascript">
//The data content that needs to be added can be obtained through ajax requestvar cities = [
{label:"xian",value:"Xi'an"},
{label:"hubei",value:"Hubei"},
{label:"wuhai",value:"Wuhan"}
]; 
//Get the datalist domvar ss = ("cities");
//Define the function to load the cityfunction loadcities(){
for(var i = 0;i < ; i ++){
var city = cities[i];
//Pure js implementation method/*var op=("option"); 
("label",);
("value",); 
(op);*/ 
//Jquery implementation method$("#cities").append('<option label="'++'" value="'++'"></option>');
}
}
//This function is loaded when the page is loaded = function(){
loadcities();
}
</script>

The above method of using js to dynamically add option options to datalist or select is all the content I share with you. I hope you can give you a reference and I hope you can support me more.