Home >Web Front-end >JS Tutorial >Tips for js to trigger select onchange event_javascript tips

Tips for js to trigger select onchange event_javascript tips

WBOY
WBOYOriginal
2016-05-16 16:40:201765browse

The onchange event of select or text needs to be manually (via keyboard input) changing the value of select or text in order to be triggered. If you assign a value to select or text in js, the onchang event cannot be triggered,
For example, after the page is loaded, an onChange event needs to be triggered. In js, it is not possible to use document.getElementById("province").value="Hubei"; to directly assign a value to select or text. If you want to manually trigger the onchange event , you need to add the following statement

after assigning a value to select in js

document.getElementById("province").fireEvent('onchange') to achieve,

<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>无标题文档</title>
<script type="text/javascript">

var provinces = new Array();
provinces["湖北"] = ["武汉","襄阳","随州","宜昌","十堰"];
provinces["四川"] = ["成都","内江","达州"];
provinces["河南"] =["郑州","南阳","信阳","漯河"];
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>
省份:<select id="province" onchange= "changeProvince()"></select>
城市:<select id="city"></select>

</body>
</html>
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