Select触发事件
案例1:
<script type="text/JavaScript"> function gradeChange(){ var objS = document.getElementById("weather-select"); var valueStr = objS.options[objS.selectedIndex].value; alert(valueStr); } </script> <select id="weather-select" style="width:100%;" onchange="gradeChange()"> <optgroup label="港澳台、直辖市"> <option value="beijing" selected>北京</option> <option value="shanghai">上海</option> <option value="tianjin">天津</option> <optgroup label="xxx"> <option value="zhongqing">重庆</option> <option value="xianggang">香港</option> </optgroup> <option value="aomen">澳门</option> <option value="taibei">台北</option> </optgroup> </select>
案例2:
js代码:
<script type="text/javascript"> var setitem = new Array(4); for(i=0;i<4;i++){ setitem[i] = new Array(); } setitem[0][0] = new Option("请选择"," "); setitem[1][0] = new Option("小学数学","小学数学"); setitem[1][1] = new Option("小学语文","小学语文"); setitem[1][2] = new Option("小学英语","小学英语"); setitem[2][0] = new Option("中学数学","中学数学"); setitem[2][1] = new Option("中学语文","中学语文"); setitem[2][2] = new Option("中学英语","中学英语"); setitem[2][3] = new Option("中学政治","中学政治"); setitem[3][0] = new Option("大学数学","大学数学"); setitem[3][1] = new Option("大学语文","大学语文"); setitem[3][2] = new Option("大学英语","大学英语"); setitem[3][3] = new Option("大学英语","大学英语"); setitem[3][4] = new Option("大学物理","大学物理"); setitem[3][5] = new Option("大学政治","大学政治"); function onS1change(index){ var sell1 = document.getElementById("sell1"); sell1.length = 0;//删除所有选项 for(i=0;i<setitem[index].length;i++){ sell1.options[i] = setitem[index][i]; } sell1.options[0].select = true; } function onS2change(str1,str2){ alert(str1+" "+str2); } </script>
<form name="form1" id="form1"> <label>您的身份是 <select name="sell" onchange="onS1change(this.value)"> <option value="0">请选择</option> <option value="1">小学生</option> <option value="2">中学生</option> <option value="3">大学生</option> </select> </label> <label>您最喜欢的科目 <select id="sell1" "> </select> </label> <br/> <input type="submit" name="Submit" onclick="onS2change(sell.value,sell1.value)"> </form>
注意点: str1是描述,str2是值
new Option("str1","str2")
<option value="这里是str2">这里是str1</option>
获取value:
var sell = document.getElementById("sell");
alert(sell.options[sell.options.selectedIndex].value);
获取text
var sell = document.getElementById("sell");
alert(sell.options[sell.options.selectedIndex].text);