js 触发select onchange事件代码
作者:
select 或text的onchange事件需要手动(通过键盘输入)改变select或text的值才能触发,本文为大家介绍下使用js触发select onchange事件
select 或text的onchange事件需要手动(通过键盘输入)改变select或text的值才能触发,如果在js中给select或text赋值,则无法触发onchang事件,
例如,在页面加载完成以后,需要触发一个onChange事件,在js中用document.getElementById("province").value="湖北";直接给select或text赋值是不行的,要想实现手动触发onchange事件,需要在js给select赋值后,加入下面的语句
document.getElementById("province").fireEvent('onchange') 来实现,
<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>
例如,在页面加载完成以后,需要触发一个onChange事件,在js中用document.getElementById("province").value="湖北";直接给select或text赋值是不行的,要想实现手动触发onchange事件,需要在js给select赋值后,加入下面的语句
document.getElementById("province").fireEvent('onchange') 来实现,
复制代码 代码如下:
<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>
您可能感兴趣的文章:
- javascript checkbox/radio onchange不能兼容ie8处理办法
- Radio 单选JS动态添加的选项onchange事件无效的解决方法
- jsp中select的onchange事件用法实例
- 纯JavaScript实现获取onclick、onchange等事件的值
- js中的onchange和onpropertychange (onchange无效的解决方法)
- js触发onchange事件的方法说明
- JavaScript获取onclick、onchange等事件值的代码
- javascript开发中使用onpropertychange,oninput事件解决onchange事件的不足
- javascript中的 onchange事件详解