Js triggers the select onchange event code

  • 2020-03-30 02:24:49
  • OfStack

The onchange event of select or text needs to change the value of select or text manually (through keyboard input) to be triggered. If the value of select or text is assigned in js, the onchang event cannot be triggered.
For example, after the page loads, an onChange event needs to be triggered. In js, document.getelementbyid (" province "). Value = "hubei"; It is not possible to assign a value to select or text directly. To manually trigger the onchange event, you need to add the following statement after js assigns a value to the select

Document.getelementbyid ("province").fireevent ('onchange'),
 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> 
<title> Headless document </title> 
<script type="text/javascript"> 
var provinces = new Array(); 
provinces[" hubei "] = [" wuhan "," xiangyang "," suizhou "," yichang "," shiyan "]; 
provinces[" sichuan "] = [" chengdu "," neijiang "," dazhou "]; 
provinces[" henan "] =[" zhengzhou "," nanyang "," xinyang "," Luo river "]; 
function changeProvince() 
{ 
var prov = document.getElementById("province").value; 
var city =document.getElementById("city"); 
city.options.length =0; 
for(var i in provinces[prov]) 
{ 
city.options.add(new Option(provinces[prov][i],provinces[prov][i])); 
} 
} 
window.onload = function(){ 
var province = document.getElementById("province"); 

for(var index in provinces) 
{ 
//alert(index); 
province.options.add(new Option(index,index)); 
} 
province.fireEvent("onchange"); 
}; 
</script> 
</head> 
<body> 
 provinces :<select id="province" onchange= "changeProvince()"></select> 
 city :<select id="city"></select> 
</body> 
</html> 

Related articles: